This is a blog post about handling circle-rectangle collisions. For some reason, these seem to be generally regarded as something complicated, even though they aren't.
First things first, you may already know how to check circle-point collision - it's simply checking that the distance between the circle' center and the point is smaller than the circle' radius:
DeltaX = CircleX - PointX; DeltaY = CircleY - PointY; return (DeltaX * DeltaX + DeltaY * DeltaY) < (CircleRadius * CircleRadius);
Surprisingly or not, rectangle-circle collisions are not all too different - first you find the point of rectangle that is the closest to the circle' center, and check that point is in the circle.
And, if the rectangle is not rotated, finding a point closest to the circle' center is simply a matter of clamping the circle' center coordinates to rectangle coordinates:
NearestX = Max(RectX, Min(CircleX, RectX + RectWidth)); NearestY = Max(RectY, Min(CircleY, RectY + RectHeight));
So, combining the above two snippets yields you a 3-line function for circle-rectangle check:
DeltaX = CircleX - Max(RectX, Min(CircleX, RectX + RectWidth)); DeltaY = CircleY - Max(RectY, Min(CircleY, RectY + RectHeight)); return (DeltaX * DeltaX + DeltaY * DeltaY) < (CircleRadius * CircleRadius);
And here's it in action, along with a bit of debug drawing:
Click and drag elements.
And that is it. I've told you that it really isn't complicated, didn't I?