二维胶囊或扫掠球体的碰撞检测

Collision Detection for 2D Capsule or Swept Sphere

我正在尝试学习如何在 2D Capsule 上以数学方式定义和检测 "hits"。

我正在定义和检测 2D 圆上的命中。这是我的 class:

class Circle
{
    private double xpos;
    private double ypos;
    private double radius;

    public Circle(double x, double y, double r)
    {
        xpos = x;
        ypos = y;
        radius = r;
    }

    public bool HitCircle(double x, double y)
    {
        bool hit = false;

        double distance = Math.Pow(x - xpos, 2) + Math.Pow(y - ypos, 2);         
        if (distance <= radius * radius) hit = true;

        return hit;
    }
}

圆是一个 x 和 y 位置以及一个半径。 HitCircle 函数是距离公式的 C# 实现。

一个胶囊被定义为 4 个点和一个半径:

class Capsule
{
    double x1pos;
    double y1pos;
    double x2pos;
    double y2pos;
    double radius;

    public Capsule(double x1, double y1, double x2, double y2, double r)
    {
        x1pos = x1;
        y1pos = y1;
        x2pos = x2;
        y2pos = y2;
        radius = r;
    }

    public bool HitCapsule(double x, double y)
    {
        bool hit = false;
        //?? This is where I need help
        return hit;
    }
}

我需要帮助来理解和实现胶囊 class 中 HitCapsule 函数的数学运算。

据我了解,胶囊就像一个圆,只是半径不是围绕单个点,而是围绕线段。

目前,我只是在尝试围绕这些几何定义中的一些进行思考。将来我可能会尝试将它变成一个简单的光线追踪器,但我想直接进入这些数学部分。

谢谢。


我不知道这是否有帮助,但这是我的 2d "raytracer." 它使用 ascii 将圆圈绘制到控制台。这有助于证明我已经正确地实现了数学运算。

    static void Main(string[] args)
    {
        double aimx = 30;
        double aimy = 8;

        Circle circle = new Circle(45, 13, 12);
        bool hit = circle.HitCircle(aimx, aimy);

        Console.WriteLine("Did we hit? {0}", hit);


        for(int y = 26; y >= 0; y--)
        {
            for(int x = 0; x < 90; x++)
            {
                if(x == aimx && y == aimy) //Draw target
                {
                    Console.Write("X");
                }
                else if(circle.HitCircle(x, y)) //Draw all circle hits
                {
                    Console.Write("#");
                }
                else
                {
                    Console.Write("-");
                }
            }
            Console.Write('\n');
        }
        Console.Read();
    }
}

点到胶囊相交是计算点到定义胶囊的线段的距离的情况。如果那是 <= r 那么你相交了。

There's a question here that shows how to find that distance,但它确实假定您熟悉向量和点积。