How to Get World Coordinates of Child Object in Three.js
In Three.js, nested 3D objects inherit the transformations of their
parents, meaning their .position property only reflects
their coordinates relative to their parent. This article explains how to
accurately convert a child object’s local coordinates into global world
coordinates using the getWorldPosition() method and the
localToWorld() utility.
Method 1: Using
getWorldPosition()
The most straightforward way to obtain the absolute world position of
a child object is by using the getWorldPosition() method.
This method extracts the translation components directly from the
object’s global transformation matrix.
Before querying the position, you must ensure that the object’s world matrix is up-to-date. Three.js updates matrices right before rendering, so manual updates are necessary if you have moved objects in the same frame.
// 1. Force an update of the object's global matrix
childObject.updateMatrixWorld(true);
// 2. Instantiate a Vector3 to store the result
const worldPosition = new THREE.Vector3();
// 3. Retrieve the world position
childObject.getWorldPosition(worldPosition);
console.log(worldPosition); // Returns the global x, y, z coordinatesMethod 2: Using
localToWorld()
If you need to convert a specific local offset (a point relative to
the child object’s origin) into world space, use the
localToWorld() method. This method applies the object’s
world matrix to a given vector.
Note that localToWorld() modifies the vector passed to
it in-place.
// 1. Force an update of the global matrix
childObject.updateMatrixWorld(true);
// 2. Define a local coordinate (e.g., 5 units up on the Y-axis relative to the child)
const localPoint = new THREE.Vector3(0, 5, 0);
// 3. Convert the local vector to world space
childObject.localToWorld(localPoint);
console.log(localPoint); // Returns the global coordinates of that offset pointThe Importance of
updateMatrixWorld()
Three.js optimizes performance by delaying matrix calculations until
the render step. If you change the position, rotation, or scale of a
parent or child object and immediately try to read its world position in
the same frame, the returned coordinates will be outdated. Calling
childObject.updateMatrixWorld(true) forces Three.js to
traverse up the scene graph and recalculate all parent-child
transformations immediately, ensuring your coordinates are 100%
accurate.