Groups & Hierarchy
A scene is a tree. Every Object3D can have children (add), and a child's position, rotation and scale are relative to its parent. Move a car and its wheels, driver and headlights come along; spin a wheel and only the wheel spins. This parent–child structure is called the scene graph, and using it well removes a lot of maths from game code.
Local and world space
- Local transform:
child.position,child.rotation,child.scale, relative to the parent. - World transform: where the object really is, the parent's world transform combined with the local one. Three.js stores it in
object.matrixWorld.
A plain-JS model in 2D (top view) shows how a world position is built from a chain of parents: rotate the child's local offset by the parent's rotation, then add the parent's position.
// World position of a point carried by a chain of parents (2D, top view, angles in degrees).
function toWorld(chain, local) {
let [x, y] = local;
for (let i = chain.length - 1; i >= 0; i--) { // innermost parent first
const { pos, angle } = chain[i];
const a = angle * Math.PI / 180;
[x, y] = [x * Math.cos(a) - y * Math.sin(a) + pos[0], x * Math.sin(a) + y * Math.cos(a) + pos[1]];
}
return `(${x.toFixed(2)}, ${y.toFixed(2)})`;
}
const ship = { pos: [10, 0], angle: 90 }; // the ship sits at (10, 0), turned 90°
const turret = { pos: [0, 2], angle: 45 }; // mounted 2 units ahead on the ship, turned 45°
const muzzle = [1.5, 0]; // barrel tip, 1.5 units along the turret's x
console.log('turret in world:', toWorld([ship], turret.pos));
console.log('muzzle in world:', toWorld([ship, turret], muzzle));
ship.angle = 180;
console.log('after the ship turns to 180°, muzzle:', toWorld([ship, turret], muzzle));turret in world: (8.00, 0.00)
muzzle in world: (6.94, 1.06)
after the ship turns to 180°, muzzle: (8.94, -3.06)
Turning the ship moved the muzzle too, without touching the turret's numbers. Three.js does exactly this with 4 × 4 matrices (matrixWorld = parent.matrixWorld × matrix) for every object, every frame.
A solar system with groups
A THREE.Group is an empty Object3D: no geometry, just a transform to hang children on. Groups are perfect pivots. To make the Moon orbit the Earth while the Earth orbits the Sun, nest pivots and rotate each one:
<style>html, body { margin: 0; height: 100%; overflow: hidden } canvas { display: block }</style>
<script type="module">
import * as THREE from 'three';
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color('#05060c');
const camera = new THREE.PerspectiveCamera(45, innerWidth / innerHeight, 0.1, 100);
camera.position.set(0, 9, 13);
camera.lookAt(0, 0, 0);
addEventListener('resize', () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
});
const sun = new THREE.Mesh(new THREE.SphereGeometry(1.2, 32, 16), new THREE.MeshBasicMaterial({ color: '#ffcc33' }));
scene.add(sun);
scene.add(new THREE.PointLight('#fff2cc', 80, 0, 2)); // sits at the sun's centre; intensity in candela
scene.add(new THREE.AmbientLight('#ffffff', 0.08));
const earthOrbit = new THREE.Group(); // pivot at the sun: rotating it carries the Earth around
scene.add(earthOrbit);
const earthSystem = new THREE.Group(); // the Earth and everything that travels with it
earthSystem.position.x = 6;
earthOrbit.add(earthSystem);
const earth = new THREE.Mesh(new THREE.SphereGeometry(0.5, 32, 16), new THREE.MeshStandardMaterial({ color: '#3d7bd9' }));
earth.rotation.z = THREE.MathUtils.degToRad(23.4); // axial tilt: only affects the Earth itself
earthSystem.add(earth);
const moonOrbit = new THREE.Group();
earthSystem.add(moonOrbit);
const moon = new THREE.Mesh(new THREE.SphereGeometry(0.15, 16, 8), new THREE.MeshStandardMaterial({ color: '#bbbbbb' }));
moon.position.x = 1.2;
moonOrbit.add(moon);
// Orbit rings for reference.
const ring = new THREE.Mesh(new THREE.RingGeometry(5.98, 6.02, 96), new THREE.MeshBasicMaterial({ color: '#334', side: THREE.DoubleSide }));
ring.rotation.x = -Math.PI / 2;
scene.add(ring);
scene.updateMatrixWorld(); // world matrices are normally updated by render(); do it now to read one
const worldPos = moon.getWorldPosition(new THREE.Vector3());
console.log('moon local position:', moon.position.toArray().join(', '), '| world position:', worldPos.toArray().map((n) => n.toFixed(2)).join(', '));
const timer = new THREE.Timer();
renderer.setAnimationLoop((t) => {
timer.update(t);
const dt = Math.min(timer.getDelta(), 0.1);
earthOrbit.rotation.y += 0.3 * dt; // a year
earth.rotation.y += 2 * dt; // a day (spins the Earth mesh only)
moonOrbit.rotation.y += 1.5 * dt; // a month
renderer.render(scene, camera);
});
</script>Notice the split between earthSystem and earth. The tilt and the daily spin belong to the Earth mesh; the Moon hangs on earthSystem, a sibling pivot, so it doesn't wobble with the Earth's tilt or whirl around once per day. Choosing what is a child of what is a design decision: put an object under the parent whose motion it should inherit, and nothing more.
Converting between spaces
| Method | Does |
|---|---|
obj.getWorldPosition(v) / getWorldQuaternion(q) / getWorldScale(v) |
the object's world transform parts |
obj.localToWorld(v) |
turns a point in obj's local space into world space (modifies v) |
obj.worldToLocal(v) |
the reverse |
parent.add(child) |
re-parents, keeping the local numbers (the child jumps if parents differ) |
parent.attach(child) |
re-parents, keeping the world transform (the child stays where it is) |
add vs attach is the difference between a bug and a feature when a character picks something up. Click Pick up below: the left crate is re-parented with add and jumps, the right one with attach and stays put, then rides along on the moving cart.
<style>html, body { margin: 0; height: 100%; overflow: hidden } canvas { display: block }
button { position: fixed; left: 8px; top: 8px; font: 13px system-ui, sans-serif }</style>
<button id="pick">Pick up</button>
<script type="module">
import * as THREE from 'three';
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color('#1a2030');
const camera = new THREE.PerspectiveCamera(45, innerWidth / innerHeight, 0.1, 100);
camera.position.set(0, 6, 11);
camera.lookAt(0, 0, 0);
scene.add(new THREE.HemisphereLight('#fff', '#334', 1.3));
const sun = new THREE.DirectionalLight('#fff', 2);
sun.position.set(3, 6, 4);
scene.add(sun);
scene.add(new THREE.GridHelper(20, 20, '#445', '#2a3040'));
function cart(x, color) {
const g = new THREE.Group();
const deck = new THREE.Mesh(new THREE.BoxGeometry(2, 0.3, 1.4), new THREE.MeshStandardMaterial({ color }));
deck.position.y = 0.35;
g.add(deck);
g.position.set(x, 0, -2);
g.rotation.y = 0.5;
scene.add(g);
return g;
}
const cartA = cart(-3, '#ef6c00'), cartB = cart(3, '#00897b');
const crateGeo = new THREE.BoxGeometry(0.7, 0.7, 0.7);
const crateA = new THREE.Mesh(crateGeo, new THREE.MeshStandardMaterial({ color: '#d7b26b' }));
const crateB = crateA.clone();
crateA.position.set(-3, 0.35, 2); // both crates sit on the floor in front of their carts
crateB.position.set(3, 0.35, 2);
scene.add(crateA, crateB);
document.getElementById('pick').onclick = (e) => {
cartA.add(crateA); // keeps local numbers (-3, 0.35, 2), now relative to the turned cart
cartB.attach(crateB); // keeps the world transform
const a = crateA.position, b = crateB.getWorldPosition(new THREE.Vector3());
console.log(`add(): local position unchanged (${a.x.toFixed(2)}, ${a.y.toFixed(2)}, ${a.z.toFixed(2)}), so it moved in the world`);
console.log(`attach(): world position unchanged (${b.x.toFixed(2)}, ${b.y.toFixed(2)}, ${b.z.toFixed(2)})`);
e.target.disabled = true;
};
const timer = new THREE.Timer();
renderer.setAnimationLoop((t) => {
timer.update(t);
const s = Math.sin(timer.getElapsed() * 0.8) * 1.5;
cartA.position.z = -2 + s;
cartB.position.z = -2 + s;
renderer.render(scene, camera);
});
</script>The crate re-parented with add keeps the numbers (-3, 0.35, 2) but now reads them in the cart's rotated, moving frame, so it teleports. attach computes the local transform that keeps the world transform unchanged. Use attach whenever something is grabbed, mounted or dropped.
Hierarchy costs and habits
- Every object's world matrix is recomputed each frame. Deep trees of thousands of objects cost CPU time; flatten static scenery or set
matrixAutoUpdate = falseon it. - Scale on a parent is inherited by everything below it. Avoid non-uniform scale (
(1, 2, 1)) on parents of rotated children: the children get skewed, and physics engines can't represent skew. - Name objects (
group.name = 'Turret') and find them later withscene.getObjectByName('Turret'); loaded glTF models arrive as named hierarchies (see glTF & GLTFLoader). object.traverse(fn)visits an object and all its descendants, the standard way to change every mesh in a model (enable shadows, swap materials, dispose).
Test yourself
A child has position.x = 2. Its parent is at x = 10 and rotated 180° around Y. Where is the child in world space (x)?
- 12
- 8
- 2
- −8
A character picks up a sword lying on the floor and it jumps to a strange place. Which call probably caused it?
hand.attach(sword)hand.add(sword)sword.updateMatrixWorld()scene.add(sword)
Why is the Moon a child of earthSystem and not of the earth mesh in the example?
- Meshes can't have children
- So it inherits the Earth's orbit but not its axial tilt and daily spin
- To make it render faster
- Groups are required for lights