2017-04-25 91 views
0

我想学习如何在数学上定义和检测2D胶囊上的“点击”。二维胶囊或扫描球的碰撞检测

我正在定义和检测2D圆上的点击。这是我的课程:

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; 
    } 
} 

我需要帮助理解和实施的胶囊类的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(); 
    } 
} 

回答

1

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

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

+0

谢谢你的链接,我正在阅读它。看起来数学变得非常令人兴奋。 – ekcell

+0

你还没有看到任何东西。这是碰撞中更简单的问题之一 –

+0

我能够使用您提供的链接获取胶囊。我仍在努力理解数学,但它确实是正确的方向。 – ekcell