How to Use Matter.Bounds.overlaps in Matter.js

This article explains how to perform an axis-aligned bounding box (AABB) intersection check in Matter.js using Matter.Bounds.overlaps. By filtering out non-colliding objects during the broad-phase stage, you can skip unnecessary, CPU-intensive narrow-phase collision calculations and optimize your physics simulation's performance.

Understanding Broad-Phase vs. Narrow-Phase

Collision detection in physics engines is typically split into two stages:

  1. Broad-Phase: Quickly checks whether the rectangular bounds (AABBs) enclosing two bodies intersect.
  2. Narrow-Phase: Performs precise mathematical checks (such as the Separating Axis Theorem) on the actual vertices of shapes whose bounding boxes intersect.

Executing narrow-phase checks for every possible pair of bodies in a scene is computationally expensive. Broad-phase checks eliminate distant pairs with minimal overhead.

Accessing Body Bounds

Every Matter.Body instance contains a bounds property representing its axis-aligned bounding box. The bounds object has min and max coordinates:

// Structure of body.bounds
{
  min: { x: number, y: number },
  max: { x: number, y: number }
}

Matter.js automatically updates body.bounds whenever a body translates, scales, or rotates.

Checking Intersections with Matter.Bounds.overlaps

The Matter.Bounds.overlaps(boundsA, boundsB) method accepts two Bounds objects and returns a boolean (true if they intersect, false otherwise).

const { Bodies, Bounds, SAT } = Matter;

// Create two rigid bodies
const boxA = Bodies.rectangle(100, 100, 50, 50);
const boxB = Bodies.rectangle(130, 100, 50, 50);

// Broad-phase check
const boundingBoxesOverlap = Bounds.overlaps(boxA.bounds, boxB.bounds);

if (boundingBoxesOverlap) {
    // Proceed to narrow-phase check
    const collision = SAT.collides(boxA, boxB);
    
    if (collision.collided) {
        console.log("Bodies are actually colliding!");
    }
} else {
    // Objects are too far apart; skip narrow-phase logic
}

Key Considerations