Get Global World Position of Child Object in Three.js

In Three.js, obtaining the exact coordinates of a deeply nested 3D object relative to the global scene, rather than its local parent, is a common challenge. This article provides a straightforward guide on how to correctly extract the global world position of any nested child object using the getWorldPosition method, ensuring your calculations are accurate even after complex transformations.

By default, an object’s .position property only returns its coordinates relative to its immediate parent. To get the absolute coordinates in the 3D world space, you must use the .getWorldPosition() method.

Here is the step-by-step process and the code required to achieve this:

1. Instantiate a Vector3 Container

Three.js requires you to pass a Vector3 object as an argument to getWorldPosition(). This design choice avoids creating new object instances in memory during runtime, which prevents performance drops from garbage collection.

import * as THREE from 'three';

// Create a target Vector3 to store the coordinates
const worldPosition = new THREE.Vector3();

2. Update the Matrix World

If your objects have recently moved, rotated, or scaled during the current frame, their global matrices might not be updated yet. To guarantee accuracy, force Three.js to recalculate the positions of the child and all of its parent objects before querying the position.

// Recursively updates the global matrix of the object and its ancestors
childObject.updateMatrixWorld(true);

3. Extract the Position

Now, call getWorldPosition() on your nested child object, passing your target vector as the argument. The method will populate your vector with the global X, Y, and Z coordinates.

// Extract the global position into our target vector
childObject.getWorldPosition(worldPosition);

// You can now use the global coordinates
console.log(`Global Position: X: ${worldPosition.x}, Y: ${worldPosition.y}, Z: ${worldPosition.z}`);