我有一个碰撞检测类,通过查找中心之间的距离以及该距离是否小到足以成为碰撞(参见Collision Detection error)。我的问题是试图使这个实际工作,椭圆碰撞。如有必要,我会解释更多。 THX
答案 0 :(得分: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游戏
答案 1 :(得分: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);
}