An algorithm for accurately detecting overlap between a square and a circle?

I implement (in C ++) a detection method when the overlap occurs between two static, axis-oriented shapes in the 2d plane. Shapes are squares or circles, and so there are three cases that I need to consider for overlapping: square square, circle circle, and circle square.

The square square and circle circle were simple enough, but I'm struggling to find any reliable information on the Internet about what the correct algorithm is for calculating the overlap of a square circle.

I know that I could embed the square inside the circle (or vice versa) as a crude method, but I am wondering what would be the cleanest way to do this more accurately?

Researching it on the Internet suggests that there is a β€œcorrect” answer to this question, but it is not clear what exactly this answer is.

+5
source share
1 answer

Here's a simple and quick 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; } } 

Please note that the square is central and half-sized.

Basically what he does:

  • it removes symmetric cases with fabs()
  • puts the corner at the beginning
  • checks what area the center of the circle is in to determine the closest point on the square of the circle. If this point closes closer than circleRadius , then overlap occurs.
+2
source

Source: https://habr.com/ru/post/1273846/


All Articles