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.
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:
fabs()
circleRadius
, then there is an overlap.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With