Circle to rectangle

We can simplify the problem of determining if a circle and rectangle intersect down to testing if a point is contained within a circle. We can do this by finding the Closest Point to the circle on the rectangle.

To find the closest point on the rectangle to the circle, if the position of the circle is outside the range of the rectangle on any axis, we clamp that point to the edge of the rectangle. The resulting point is guaranteed to be on the rectangle. If this point is inside the circle, we know a collision has happened.

If the center point of the circle was inside of the rectangle, it is treated as the closest point. In this case, the distance between the position of the circle and the closest point will be zero:

Getting ready ...

Get Game Physics Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.