Box-Box Intersection

The purpose of this interactive demonstration is the visualization of the code for intersection of two axis-aligned bounding boxes (AABBs) in 2D. This approach can easily be extended to work in 3D space.

The function intersect() detects the intersection of two AABBs by checking if the intervals overlap on both the x and y axes. Once an intersection is detected, the functions overlapSize() and resolveCollision() resolve the collision of the boxes along the axis of minimum penetration. In the following code, Booleans are underlined in red if they are false and in green if they are true.

class BoundingBox {
public:
  Vec2 min;
  Vec2 max;

  bool intersect(const BoundingBox& b) const {
    bool overlapX = (min.x <= b.max.x) && (max.x >= b.min.x);
    bool overlapY = (min.y <= b.max.y) && (max.y >= b.min.y);
    return (overlapX && overlapY);
  }

  Vec2 overlapSize(const BoundingBox& b) const {
    Vec2 result(0, 0);
    if (min.x < b.min.x) { // X-dimension 
      result.x = max.x - b.min.x; 
    } else {
      result.x = b.max.x - min.x; 
    }
    if (min.y < b.min.y) { // Y-dimension
      result.y = max.y - b.min.y; 
    } else {
      result.y = b.max.y - min.y; 
    }
    return result;
  }

  Vec2 resolveCollision(const BoundingBox& b) const {
    Vec2 resolveVec(0, 0);
    // assuming this class is the dynamic box, and "b" is the static box
    Vec2 overlap = overlapSize(b);
    // compute the centers
    Vec2 center = (min + max) * 0.5;
    Vec2 staticCenter = (b.min + b.max) * 0.5;
    // resolve collision along the axis of minimum penetration
    if (overlap.x < overlap.y) {
      resolveVec.x = (center.x < staticCenter.x) ? -overlap.x : overlap.x;
    } else {
      resolveVec.y = (center.y < staticCenter.y) ? -overlap.y : overlap.y;
    }
    return resolveVec;
  }
};

This website is a part of the Graphics Programming lecture at the University of Marburg.
Author: Thorsten ThormählenLegal NoticePrivacy Policy