Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm for accurate detection of overlap between a square and a circle? [duplicate]

I am implementing (in C++) a method to detect when an overlap is occurring between two static, axis-aligned shapes on a 2d plane. The shapes are either squares or circles, and therefore there are three cases I need to consider for overlap: square-square, circle-circle, and circle-square.

Square-square and circle-circle were simple enough, but I am struggling to find any solid information online about what the correct algorithm is for calculating square-circle overlap.

I am aware that I could embed the square inside a circle (or vice versa) as a rough method, but I'm interested in what would be considered the cleanest way to do this more precisely?

Researching it online suggests there is a 'correct' answer to this question, but it isn't made clear what exactly that answer is.

like image 704
transiti0nary Avatar asked Oct 28 '22 22:10

transiti0nary


1 Answers

Here's a simple and fast algorithm:

bool doesSquareCircleOverlap(float squareCenterX, float squareCenterY, float squareHalfSize, float circleCenterX, float circleCenterY, float circleRadius) {
    float x = fabs(circleCenterX - squareCenterX) - squareHalfSize;
    float y = fabs(circleCenterY - squareCenterY) - squareHalfSize;

    if (x>0) {
        if (y>0) {
            return x*x + y*y<circleRadius*circleRadius;
        } else {
            return x<circleRadius;
        }
    } else {
        return y<circleRadius;
    }
}

Note that the square is represented by the center and half-size.

Basically, what it does is:

  • it removes symmetrical cases with fabs()
  • puts the corner into the origin
  • checks which area the center of circle is, to determine the closest point on the square from the circle. If this closes point is nearer than circleRadius, then there is an overlap.
like image 131
geza Avatar answered Nov 15 '22 07:11

geza