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?

Bonus: Visualization ported to GameMaker

### Related posts:

This is beautifully simple. Thanks for sharing it, and I love the interactive demo!

Excellent algorithm, explanation and demo! Thank you for sharing it!

what are the rectangles points? is it the center?

It’s top-left and bottom-right corners of the rectangle – in other words, bounds of it.

Hi there! I’ve been searching for ages for this! I’m not really a math person so even if this looked really simple, I can’t seem to understand how to apply this into my code. Are you willing to share the project file with me? I need to also see the debug drawing to understand it.

You can right-click on the page, pick “View source”, and scroll down to

document.getElementById("canvas-605"). That’s exactly how the demo code was written – right in the blog post.Thanks for getting back! And I just saw it. This may seem silly.. but how do I translate that into GML?

In GameMaker you wouldn’t need it at all, since there is a built-in rectangle_in_circle for this.

Here’s the demo ported to GML.

This is way to simple ^^ its something i have been thinking about for some time, but this is really qute nice 🙂

Awesome!

Thank you very much, author!

Big fan of your stuff, especially this article. Thank you for making it. : )