Search code examples
mathgeometrycollision-detection

Circle-Rectangle's border collision detection


How can I tell whether a circle tangents the outer rectangle or is located (partially) outside of the rectangle in 2D Euclidean space?

The rectangle will always be aligned with the axes. Visual representation of a circle-rectangle's border collision

Basically I'm creating a simple game with a ball which moves in certain steps with a certain angle through the space.


Solution

  • Let's denote the four sides of the rectangle s1, s2, s3, s4 starting from the top and moving clockwise.

    Check the distance from the circle's centre to each of the four lines; d1, d2, d3, d4 (numbered corresponding to the sides). Note that there is a simple formula to derive the (orthogonal) distance from a point to a line.

    A necessary (although not sufficient) condition is that the distance from one of the lines is the radius length (pragmatically the difference is less than some delta of your choosing):
    |d1 - r| < delta || ...

    You can make this a sufficient condition if the circle is totally inside the rectangle, which is true iff each distance is less than the distance between the corresponding sides of the rectangle, less the radius:
    d1 <= |s1 - s3|-r && d2 <= |s2 - s4|-r && ...

    Checking partially outside is as simple as checking for the opposite of the last paragraph (and if you require, checking that the radius is still within the box):
    d1 > |s1 - s3|-r || d2 > |s2 - s4|-r || ...