Calculate Distance Between Two Three.js Objects
This article explains how to accurately calculate the 3D distance
between two independent Object3D instances in Three.js. You
will learn how to retrieve their global world coordinates—even if they
are nested inside different parent groups—and use the Three.js vector
mathematics API to compute the precise Euclidean distance between
them.
The Challenge of Local vs. World Coordinates
In Three.js, the .position property of an
Object3D represents its position relative to its parent
(local space). If your objects are nested inside different groups,
comparing their .position properties directly will yield
incorrect results. To get the precise distance, you must first determine
their coordinates in global 3D space (world space).
Step-by-Step Distance Calculation
To calculate the precise distance between objectA and
objectB, follow these three steps:
1. Update the World Matrices
Before querying world positions, ensure that Three.js has calculated
the latest transformations for both objects. If the objects or their
parents have moved during the current frame, call
updateMatrixWorld() to force an immediate
recalculation.
objectA.updateMatrixWorld(true);
objectB.updateMatrixWorld(true);2. Extract World Positions
Create two instances of THREE.Vector3 to store the
target coordinates. Use the .getWorldPosition() method to
extract the world space coordinates of each object into these
vectors.
const vectorA = new THREE.Vector3();
const vectorB = new THREE.Vector3();
objectA.getWorldPosition(vectorA);
objectB.getWorldPosition(vectorB);3. Calculate the Distance
Once you have the world positions, use the .distanceTo()
method of the Vector3 class to calculate the straight-line
distance between the two points.
const distance = vectorA.distanceTo(vectorB);
console.log(`The precise distance is: ${distance}`);Optimization for Performance-Critical Code
If you are running this calculation inside an animation loop
(requestAnimationFrame) and only need to compare distances
(for example, to check if an object is within a certain range), use
.distanceToSquared() instead of
.distanceTo().
Calculating the exact distance requires a square root operation, which is computationally expensive. Comparing squared distances avoids this operation:
const squaredDistance = vectorA.distanceToSquared(vectorB);
const targetRange = 5;
// Compare with the square of your target range
if (squaredDistance < (targetRange * targetRange)) {
console.log("The objects are within range.");
}