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:
- Broad-Phase: Quickly checks whether the rectangular bounds (AABBs) enclosing two bodies intersect.
- 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
- False Positives: Because bounding boxes are
axis-aligned, rotating a body expands its bounding box. Two bounding
boxes may overlap even if the physical geometries do not touch. Always
follow up with narrow-phase algorithms (like
Matter.SAT.collidesorMatter.Collision.collides) if exact collision data is required. - Static Bodies: Ensure that any custom movement
applied to static bodies triggers a bounds update using
Matter.Body.updateBounds(body)if done manually outside the standard engine update loop. - Bulk Checks: When handling many bodies, pair
Matter.Bounds.overlapswith a spatial grid or BVH (Bounding Volume Hierarchy) structure rather than testing all pairs via nested loops (\(O(n^2)\)).