I have a collision detection class that works by finding the distance between the centres and whether that distance is small enough to be a collision (see Collision Detection error). My problem is trying to make this actually work, with ellipses colliding. I will explain more if necessary. Thx
The best way would to implement per pixel collision detection when the images are overlapping you can read more about this in the following links
http://www.codeproject.com/KB/game/collision3.aspx
Per-pixel collision problem in C#
I also did a problem like this for a project a few years ago when I needed to detect if two circles overlapped where i used the following code
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;
}
Not very nice code but I wrote it doing my first XNA game
I had the same problem recently. Circle overlap is easy to determine. With ellipses it's trickier, but not that bad. You play around with the ellipse equation for a while, and the result comes up:
//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);
}
来源:https://stackoverflow.com/questions/3540472/collision-detection-implementation