How to Use Matter.SAT.collides in Matter.js
This guide explains how to use the Matter.SAT.collides
method directly in Matter.js to perform collision detection between two
standalone rigid bodies. By tapping into Matter.js's underlying
Separating Axis Theorem (SAT) module, you can determine whether two
shapes intersect, calculate overlap depth, and retrieve collision
normals without needing an active Matter.Engine,
Matter.World, or physics loop.
Understanding Matter.SAT.collides
The Matter.SAT module implements the Separating Axis
Theorem to detect convex polygon and circle intersections. When you run
a full physics simulation, Matter.js invokes this module under the hood.
Calling Matter.SAT.collides(bodyA, bodyB) directly allows
you to check for instantaneous collisions between two isolated bodies at
their current positions and orientations.
Basic Implementation
To perform a direct collision test, instantiate two bodies using the
Matter.Bodies module and pass them to
Matter.SAT.collides.
// Import modules if using a module bundler, or access via the global Matter object
const { Bodies, Body, SAT } = Matter;
// 1. Create two standalone bodies
const boxA = Bodies.rectangle(100, 100, 50, 50);
const boxB = Bodies.rectangle(120, 100, 50, 50);
// 2. Perform the collision check
const collision = SAT.collides(boxA, boxB);
// 3. Inspect the result
if (collision && collision.collided) {
console.log("Collision detected!");
console.log("Penetration depth:", collision.depth);
console.log("Collision normal:", collision.normal);
} else {
console.log("No collision detected.");
}Inspecting the Collision Result
The function returns a collision object containing detailed data about the intersection:
collided: A boolean indicating whether the two bodies overlap (true) or not (false).depth: A number representing the minimum distance required to separate the two bodies along the collision normal.normal: A vector{ x, y }pointing in the direction of the minimum translation vector to resolve the overlap.bodyA/bodyB: References to the two bodies involved in the test.supports: An array of vertex vectors representing the points of contact between the bodies.
If there is no overlap, collision.collided will be
false, and depth will be 0.
Important Considerations for Standalone Bodies
When moving or rotating standalone bodies outside of an engine loop,
do not modify body.position.x or
body.position.y directly. Doing so will not update the
underlying geometry that the SAT algorithm relies on.
Always use the official Matter.Body manipulation
functions:
- Use
Body.setPosition(body, { x, y })to move a body. - Use
Body.setAngle(body, angleInRadians)to rotate a body. - Use
Body.scale(body, scaleX, scaleY)to resize a body.
These methods recalculate the body's vertex positions and axis
normals, ensuring Matter.SAT.collides receives accurate
geometric data for its calculations.