Get World Quaternion of Child Object in Three.js
Extracting the global rotation of a nested child object in Three.js
is a common task when working with complex 3D hierarchies. This article
explains how to use the Object3D.getWorldQuaternion()
method to accurately retrieve a child object’s world rotation, bypassing
its local transform inheritance. You will learn how to prepare the
target quaternion, ensure the scene’s matrices are up to date, and
extract the final global rotation values.
In Three.js, child objects inherit the transformations (position,
rotation, and scale) of their parent objects. While the
.quaternion property of a child object only returns its
local rotation relative to its parent, the
.getWorldQuaternion() method allows you to extract its
absolute rotation in the 3D world space.
Step 1: Instantiate a Target Quaternion
To avoid constant memory allocation and garbage collection overhead,
Three.js requires you to pass a target Quaternion object
into the .getWorldQuaternion() method. The method will
modify this target object in place.
import * as THREE from 'three';
// Create a reusable Quaternion object to store the result
const globalQuaternion = new THREE.Quaternion();Step 2: Update the Matrix World
Before querying the global transformation of any object, you must ensure that Three.js has calculated the world matrices for the object and its ancestors. If the object or its parents have moved or rotated in the current frame, the world matrix might be outdated.
Force an update by calling updateMatrixWorld() on the
child object or the scene:
// Force-update the child's world matrix and its ancestors
childObject.updateMatrixWorld(true);Step 3: Extract the World Quaternion
Once the matrices are updated, call getWorldQuaternion()
on the child object, passing your target quaternion as the argument.
// Extract the global rotation into your target variable
childObject.getWorldQuaternion(globalQuaternion);
// The globalQuaternion variable now holds the absolute world rotation
console.log(globalQuaternion);Complete Code Example
Here is a complete, concise implementation showing how to safely extract the global rotation of a nested mesh:
import * as THREE from 'three';
// Setup a simple hierarchy
const parent = new THREE.Group();
const child = new THREE.Mesh(new THREE.BoxGeometry(), new THREE.MeshBasicMaterial());
parent.add(child);
parent.rotation.set(Math.PI / 4, 0, 0); // Rotate parent
child.rotation.set(0, Math.PI / 4, 0); // Rotate child locally
// 1. Create the target holder
const targetQuaternion = new THREE.Quaternion();
// 2. Update matrices to ensure accuracy
child.updateMatrixWorld(true);
// 3. Get the absolute global rotation
child.getWorldQuaternion(targetQuaternion);
console.log('Global Quaternion:', targetQuaternion);