Game Development Reference
In-Depth Information
Checking for overlap in the rectangle case looks complex at first. However, we can create a very
simple test if we use a little logic. Here's the simplest method to check for overlap between two
rectangles:
public 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 &&
r1.lowerLeft.y + r1.height > r2.lowerLeft.y)
return true ;
else
return false ;
}
This looks a little confusing at first sight, so let's go over each condition. The first condition
states that the left edge of the first rectangle must be to the left of the right edge of the second
rectangle. The next condition states that the right edge of the first rectangle must be to the right
of the left edge of the second rectangle. The other two conditions state the same for the top and
bottom edges of the rectangles. If all these conditions are met, then the two rectangles overlap.
Double-check this with Figure 8-14 . It also covers the containment case.
Circle/Rectangle Collision
Can we check for overlap between a circle and a rectangle? Yes, we can. However, this is a little
more involved. Take a look at Figure 8-15 .
Figure 8-15. Overlap-testing a circle and a rectangle by finding the point on/in the rectangle that is closest to the circle
The overall strategy to test for overlap between a circle and a rectangle goes like this:
ï?®
Find the x coordinate on or in the rectangle that is closest to the circle's
center. This coordinate can be a point either on the left or right edge of the
rectangle, unless the circle center is contained in the rectangle, in which
case the closest x coordinate is the circle center's x coordinate.
ï?®
Find the y coordinate on or in the rectangle that is closest to the circle's
center. This coordinate can be a point either on the top or bottom edge of
the rectangle, unless the circle center is contained in the rectangle, in which
case the closest y coordinate is the circle center's y coordinate.
ï?®
If the point composed of the closest x and y coordinates is within the circle,
the circle and rectangle overlap.
 
Search WWH ::




Custom Search