2010-08-22 42 views
1

我有一个碰撞检测类,通过查找中心之间的距离以及该距离是否足够小而成为碰撞来工作(请参阅Collision Detection error)。我的问题是试图使这个实际工作,椭圆相互碰撞。如有必要,我会解释更多。 THX碰撞检测实现

+0

谁做指定椭圆的位置(旋转等)?还是你的意思是圈子? – raisyn 2010-08-22 08:00:49

回答

2

最好的办法时,图像重叠,您可以在以下链接

http://www.codeproject.com/KB/game/collision3.aspx

Per-pixel collision problem in C#

我也做了一个问题,了解更多关于这个每个像素碰撞检测来实现像几年前的一个项目,当我需要检测两个圆圈是否重叠时,我使用以下代码

public static bool Intersect(Rectangle rectangle1, Rectangle rectangle2) 
    { 
     if (((rectangle1.X < (rectangle2.X + rectangle2.Width)) && (rectangle2.X < (rectangle1.X + rectangle1.Width))) && (rectangle1.Y < (rectangle2.Y + rectangle2.Height)) && (rectangle2.Y < (rectangle1.Y + rectangle1.Height))) 
     { 
      Vector2 rect1Centre = new Vector2(rectangle1.X + rectangle1.Width/2, rectangle1.Y + rectangle1.Height/2); 
      Vector2 rect2Centre = new Vector2(rectangle2.X + rectangle2.Width/2, rectangle2.Y + rectangle1.Height/2); 
      double radius1 = ((rectangle1.Width/2) + (rectangle1.Height/2))/2; 
      double radius2 = ((rectangle2.Width/2) + (rectangle2.Height/2))/2; 

      double widthTri = rect1Centre.X - rect2Centre.X; 
      double heightTri = rect1Centre.Y - rect2Centre.Y; 
      double distance = Math.Sqrt(Math.Pow(widthTri, 2) + Math.Pow(heightTri, 2)); 

      if (distance <= (radius1 + radius2)) 
       return true; 
     } 
     return false; 
    } 

不是很好的代码,但我写它做我的第一个XNA游戏

+0

rectangle1.X是矩形中心的X坐标,rectangle1.Y是Y坐标 – 2010-08-22 10:53:33

+0

干杯人,但我怎样才能使它适用于现有的对象,而不是由方法创建的? – Apophis 2010-08-23 04:05:46

+0

@NeoHaxxor我真的要看你有多少物品,我只有3个圈子(这是一个空气曲棍球游戏),所以我每次都有一个事件处理程序,每次移动时我都会对其他矩形进行检查。如果你有很多需要检查的对象,可能有更好的方法。 – 2010-08-23 10:44:58

2

我最近有同样的问题。圆圈重叠很容易确定。使用省略号更加棘手,但并不那么糟糕。你玩椭圆方程一段时间,结果出现:

//Returns true if the pixel is inside the ellipse 
public bool CollisionCheckPixelInEllipse(Coords pixel, Coords center, UInt16 radiusX, UInt16 radiusY) 
{ 
    Int32 asquare = radiusX * radiusX; 
    Int32 bsquare = radiusY * radiusY; 
    return ((pixel.X-center.X)*(pixel.X-center.X)*bsquare + (pixel.Y-center.Y)*(pixel.Y-center.Y)*asquare) < (asquare*bsquare); 
} 

// returns true if the two ellipses overlap 
private bool CollisionCheckEllipses(Coords center1, UInt16 radius1X, UInt16 radius1Y, Coords center2, UInt16 radius2X, UInt16 radius2Y) 
{ 
    UInt16 radiusSumX = (UInt16) (radius1X + radius2X); 
    UInt16 radiusSumY = (UInt16) (radius1Y + radius2Y); 

    return CollisionCheckPixelInEllipse(center1, center2, radiusSumX, radiusSumY); 
} 
+0

干杯的人。还有一件事 - 能够使该方法触发translatetransform方法?代码的细节不是问题,我编码它,只是让上面的代码返回true并触发此代码。谢谢 – Apophis 2010-08-23 04:34:12