Distance Between Vectors Using Matter.Vector.magnitude
In Matter.js, calculating the Euclidean distance between two
arbitrary points or bodies is a common requirement for proximity checks,
range-based triggers, and custom constraints. While Matter.js does not
provide a standalone Vector.distance method, you can easily
determine the straight-line distance by finding the difference between
two vectors and measuring its length using
Matter.Vector.magnitude. This guide demonstrates how to
combine these built-in vector methods to compute the exact Euclidean
distance.
The Mathematical Concept
The Euclidean distance between two 2D points, \(A(x_1, y_1)\) and \(B(x_2, y_2)\), is defined as:
\[\text{Distance} = \sqrt{(x_2 - x_1)^2 + (y_2 - y_1)^2}\]
In vector mathematics, subtracting Vector \(B\) from Vector \(A\) yields a displacement vector representing the path from \(B\) to \(A\):
\[\vec{D} = (x_1 - x_2, y_1 - y_2)\]
The length (or magnitude) of this displacement vector is mathematically identical to the Euclidean distance between the two points.
Implementation in Matter.js
To calculate the distance between two vectors using the Matter.js Vector module:
- Subtract one vector from the other using
Matter.Vector.sub(vectorA, vectorB). - Pass the resulting displacement vector into
Matter.Vector.magnitude(displacement).
const Vector = Matter.Vector;
// Define two arbitrary 2D vectors
const vectorA = { x: 10, y: 20 };
const vectorB = { x: 40, y: 60 };
// Step 1: Calculate the displacement vector
const displacement = Vector.sub(vectorB, vectorA);
// Step 2: Compute the Euclidean distance
const distance = Vector.magnitude(displacement);
console.log(`Euclidean Distance: ${distance}`); // Output: 50Helper Function
You can wrap this logic into a reusable helper function:
function getDistance(vectorA, vectorB) {
return Matter.Vector.magnitude(Matter.Vector.sub(vectorB, vectorA));
}
// Example usage with Matter.js bodies
const bodyA = Matter.Bodies.circle(100, 100, 20);
const bodyB = Matter.Bodies.circle(250, 300, 20);
const distanceBetweenBodies = getDistance(bodyA.position, bodyB.position);
console.log(`Distance: ${distanceBetweenBodies}`);Performance Tip:
magnitudeSquared
Calling Matter.Vector.magnitude internally uses
Math.sqrt(), which can be computationally expensive inside
tight physics loops (such as collision detection routines checking
hundreds of bodies per frame).
If you only need to compare distances (e.g., checking if an object is
within a certain radius \(R\)),
consider using Matter.Vector.magnitudeSquared and comparing
the result against \(R^2\):
const displacement = Matter.Vector.sub(vectorB, vectorA);
const distanceSquared = Matter.Vector.magnitudeSquared(displacement);
const radius = 50;
// Comparing squared values avoids the Math.sqrt() calculation
if (distanceSquared <= radius * radius) {
// vectorB is within range of vectorA
}