Calculate Distance Between Matter.js Bodies
Calculating the distance between two physics bodies in Matter.js
involves finding the Euclidean distance between their position vectors.
This article explains how to determine this distance using both
Matter.js's built-in Matter.Vector utilities and vanilla
JavaScript math, as well as how to account for body dimensions when
measuring surface-to-surface distance.
Accessing Body Positions
Every body in Matter.js has a position property
representing its center of mass as a 2D vector
{ x, y }.
const bodyA = Bodies.circle(100, 100, 20);
const bodyB = Bodies.circle(400, 500, 20);
console.log(bodyA.position); // { x: 100, y: 100 }
console.log(bodyB.position); // { x: 400, y: 500 }Method 1: Using Matter.Vector (Recommended)
Matter.js provides a native Vector module with built-in
math operations. You can subtract the two position vectors to get the
displacement, and then calculate the magnitude of the resulting
vector.
const Matter = require('matter-js'); // or window.Matter
const Vector = Matter.Vector;
// Calculate displacement vector
const displacement = Vector.sub(bodyB.position, bodyA.position);
// Calculate the scalar distance
const distance = Vector.magnitude(displacement);
console.log(`Distance: ${distance}`);Method 2: Using the Pythagorean Theorem
For performance-critical loops (such as running inside the
beforeUpdate event for hundreds of bodies), you can avoid
creating intermediate vector objects by calculating the distance
directly using the standard distance formula:
\[\text{distance} = \sqrt{(x_2 - x_1)^2 + (y_2 - y_1)^2}\]
function getDistance(bodyA, bodyB) {
const dx = bodyB.position.x - bodyA.position.x;
const dy = bodyB.position.y - bodyA.position.y;
return Math.sqrt(dx * dx + dy * dy);
}
const distance = getDistance(bodyA, bodyB);Optimizing with Squared Distance
If you only need to compare distances (such as checking if two bodies
are within a certain interaction range), omit Math.sqrt()
to save CPU cycles:
function getDistanceSquared(bodyA, bodyB) {
const dx = bodyB.position.x - bodyA.position.x;
const dy = bodyB.position.y - bodyA.position.y;
return dx * dx + dy * dy;
}
const threshold = 150;
if (getDistanceSquared(bodyA, bodyB) < threshold * threshold) {
// Bodies are within 150 units of each other
}Calculating Edge-to-Edge Distance
The methods above calculate the distance between the centers of the bodies. If you need the distance between the surfaces of two circular bodies, subtract their radii from the total distance:
const centerDistance = Vector.magnitude(Vector.sub(bodyB.position, bodyA.position));
const edgeDistance = centerDistance - (bodyA.circleRadius + bodyB.circleRadius);
if (edgeDistance <= 0) {
// The circles are touching or overlapping
}