I have this formula for simple circle collision detection:
private bool CircleCollision(Rectangle Circle1, Rectangle Circle2)
{
int X1 = Circle1.Left;
int Y1 = Circle1.Top;
int X2 = Circle2.Left;
int Y2 = Circle2.Top;
int R1 = Circle1.Width / 2;
int R2 = Circle2.Width / 2;
int Radius = R1 + R2;
int dX = X2 - X1;
int dY = Y2 - Y1;
if (Math.Sqrt((dX * dX) + (dY * dY)) <= Math.Sqrt(Radius * Radius))
return true;
else
return false;
}
But it just expose detection whenever the two circles have same radius. What am I doing wrong?
Solved
int X1 = Circle1.Left + (Circle1.Width / 2);
int Y1 = Circle1.Top + (Circle1.Height / 2);
int X2 = Circle2.Left + (Circle2.Width / 2);
int Y2 = Circle2.Top + (Circle2.Height / 2);
To check if two circles overlap you can do:
Note that I’m calculating the distance of the centers, not of the top left corners. I’m also comparing with the squared radius so I don’t need to use the expensive
Math.Sqrtfunction, but that doesn’t affect correctness.Your code doesn’t work because you use
LeftandTopinstead of the position of the center. The difference between the top-left corners is the same as the difference between the centers if the radius is the same. This explains why your code only works in that special case.Not sure why you use a rectangle to represent a circle. You can calculate the center as
centerX = 0.5*(Left+Right). You should also add a check thatWidth==Height, else you might get an ellipse as parameter, and then this algorithm won’t work.