MahanGM
MahanGM

Reputation: 2382

Circle collision formula

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

Upvotes: 0

Views: 4565

Answers (1)

CodesInChaos
CodesInChaos

Reputation: 108800

To check if two circles overlap you can do:

var radius=circle1.Radius+circle2.Radius;
var deltaX=circle1.CenterX-circle2.CenterX;
var deltaY=circle1.CenterY-circle2.CenterY;
return deltaX*deltaX + deltaY*deltaY <= radius*radius;

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.Sqrt function, but that doesn't affect correctness.

Your code doesn't work because you use Left and Top instead 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 that Width==Height, else you might get an ellipse as parameter, and then this algorithm won't work.

Upvotes: 3

Related Questions