-
Notifications
You must be signed in to change notification settings - Fork 8
Rectangle collision 2D
The simplest form of rectangle collision is overlap, and when the rectangles are axis aligned it is the easiest. This is also known as AABB, or axis-aligned bounding boxes.
Starting with rectangles r1 and r2 we perform 4 exclusion checks.
If the left edge of r1 is farther right than the right edge of r2, there is no collision and no overlap.
if (r1.X() > r2.RX()) {collision = false;}
We repeat this for the other pairs of sides of the two rectangles.
The second check is if the top of r1 is lower than the bottom of r2.
Check 3 is if the right edge of r1 is farther left than the left edge of r2.
The final check is if the bottom edge of r1 is higher than the top edge of r2.
If any of these 4 checks are true, the rectangles do not overlap.
We can simplify this into a single function to check for rectangle overlap. Pseudo code :
bool RectanglesOverlap(const Rectangle& r1 , const Rectangle& r2) {
return (!(r1.X() > r2.RX() ||
r1.Y() > r2.BY() ||
r1.RX() < r2.X() ||
r1.BY() < r2.Y()));
}
Back to Collision Detection 2D