Game Development Reference
In-Depth Information
While not depicted in Figure
8-15
, this method also works for circles that completely contain the
rectangle. Here's the code:
public boolean
overlapCircleRectangle(Circle c, Rectangle r) {
float
closestX = c.center.x;
float
closestY = c.center.y;
if
if(c.center.x < r.lowerLeft.x) {
closestX = r.lowerLeft.x;
}
else if
if(c.center.x > r.lowerLeft.x + r.width) {
closestX = r.lowerLeft.x + r.width;
}
if
if(c.center.y < r.lowerLeft.y) {
closestY = r.lowerLeft.y;
}
else if
if(c.center.y > r.lowerLeft.y + r.height) {
closestY = r.lowerLeft.y + r.height;
}
return
c.center.distSquared(closestX, closestY) < c.radius * c.radius;
}
The description looked a lot scarier than the implementation. We determine the closest point on
the rectangle to the circle and then simply check whether the point lies inside the circle. If that's
the case, there is an overlap between the circle and the rectangle.
Note that we add an overloaded
distSquared()
method to
Vector2
that takes two float
arguments instead of another
Vector2
. We do the same for the
dist()
function.
Putting It All Together
Checking whether a point lies inside a circle or rectangle can also be useful. We can code up
two more methods and put them in a class called
OverlapTester
, together with the other three
methods we just defined. Listing 8-6 shows the code.
Listing 8-6. OverlapTester.java; Testing Overlap Between Circles, Rectangles, and Points
package
com.badlogic.androidgames.framework.math;
public class
OverlapTester {
public static boolean
overlapCircles(Circle c1, Circle c2) {
float
distance = c1.center.distSquared(c2.center);
float
radiusSum = c1.radius + c2.radius;
return
distance <= radiusSum * radiusSum;
}
public static boolean
overlapRectangles(Rectangle r1, Rectangle r2) {
if
(r1.lowerLeft.x < r2.lowerLeft.x + r2.width &&
r1.lowerLeft.x + r1.width > r2.lowerLeft.x &&
r1.lowerLeft.y < r2.lowerLeft.y + r2.height &&