Quaternions & lookAt
Euler angles are fine for a door or a turret that only turns around one axis. As soon as things turn freely (a ship that banks and climbs, an enemy that smoothly turns to face you, a physics body tumbling down a hill), you want quaternions: four numbers (x, y, z, w) that store a rotation without gimbal lock and interpolate smoothly. You never need to read the four numbers; you need about five operations.
The five operations you will use
| Task | Three.js |
|---|---|
Rotation of angle around a unit axis |
q.setFromAxisAngle(axis, angle) |
| From Euler angles / to Euler angles | q.setFromEuler(euler) / euler.setFromQuaternion(q) |
Apply rotation a, then rotation b (both in world terms) |
q.copy(a).premultiply(b), which is b × a |
| Rotate a vector | v.applyQuaternion(q) |
| Blend between two rotations | q.slerp(target, t) or q.rotateTowards(target, maxAngle) |
object.quaternion and object.rotation are linked: setting one updates the other. Physics engines hand you quaternions, so syncing a mesh to a body is mesh.quaternion.copy(body.quaternion).
The maths behind them fits in a few lines. This plain-JS model builds quaternions from axis–angle pairs, combines them and rotates a vector, the same way Three.js does:
// Minimal quaternion maths: [x, y, z, w].
const fromAxisAngle = ([ax, ay, az], angle) => {
const s = Math.sin(angle / 2);
return [ax * s, ay * s, az * s, Math.cos(angle / 2)];
};
const mul = ([ax, ay, az, aw], [bx, by, bz, bw]) => [ // a × b: apply b first, then a
aw * bx + ax * bw + ay * bz - az * by,
aw * by - ax * bz + ay * bw + az * bx,
aw * bz + ax * by - ay * bx + az * bw,
aw * bw - ax * bx - ay * by - az * bz,
];
const rotate = (q, [x, y, z]) => { // q × (v, 0) × conjugate(q)
const r = mul(mul(q, [x, y, z, 0]), [-q[0], -q[1], -q[2], q[3]]);
return r.slice(0, 3);
};
const fmt = (a) => `(${a.map((n) => (Math.abs(n) < 5e-7 ? 0 : n).toFixed(3)).join(', ')})`;
const yaw90 = fromAxisAngle([0, 1, 0], Math.PI / 2); // turn left 90° around Y
const pitch90 = fromAxisAngle([1, 0, 0], Math.PI / 2); // tip 90° around X
console.log('yaw90 ', fmt(yaw90));
console.log('forward (0,0,1) after yaw90:', fmt(rotate(yaw90, [0, 0, 1])));
console.log('yaw then pitch:', fmt(rotate(mul(pitch90, yaw90), [0, 0, 1])));
console.log('pitch then yaw:', fmt(rotate(mul(yaw90, pitch90), [0, 0, 1])));yaw90 (0.000, 0.707, 0.000, 0.707)
forward (0,0,1) after yaw90: (1.000, 0.000, 0.000)
yaw then pitch: (1.000, 0.000, 0.000)
pitch then yaw: (0.000, -1.000, 0.000)
Two lessons hide in that output. A 90° turn is stored as sin(45°) ≈ 0.707 and cos(45°) ≈ 0.707: quaternions use half angles. And the order of multiplication matters: yawing first leaves the nose pointing along +X, where a pitch around world X does nothing to it; pitching first points the nose down (−Y), and a yaw around the vertical axis leaves it there. Quaternions in Math for Games derives the formulas.
The same thing with THREE.Quaternion
The Three.js classes do the same job (the console is under the frame; there is nothing to draw):
<script type="module">
import * as THREE from 'three';
const up = new THREE.Vector3(0, 1, 0), right = new THREE.Vector3(1, 0, 0);
const yaw = new THREE.Quaternion().setFromAxisAngle(up, Math.PI / 2);
const pitch = new THREE.Quaternion().setFromAxisAngle(right, Math.PI / 2);
const f = (v) => v.toArray().map((n) => (Math.abs(n) < 5e-7 ? 0 : n).toFixed(3)).join(', ');
console.log('yaw quaternion:', f(new THREE.Vector4(yaw.x, yaw.y, yaw.z, yaw.w)));
console.log('forward after yaw:', f(new THREE.Vector3(0, 0, 1).applyQuaternion(yaw)));
// premultiply: "then apply this one". yaw, then pitch:
const yawThenPitch = yaw.clone().premultiply(pitch);
console.log('yaw then pitch:', f(new THREE.Vector3(0, 0, 1).applyQuaternion(yawThenPitch)));
// Euler <-> quaternion stay in sync on an Object3D.
const obj = new THREE.Object3D();
obj.quaternion.copy(yaw);
console.log('rotation.y in degrees:', THREE.MathUtils.radToDeg(obj.rotation.y).toFixed(1));
// Halfway between no rotation and the yaw: 45°.
const half = new THREE.Quaternion().slerp(yaw, 0.5);
console.log('slerp 0.5 ->', (THREE.MathUtils.radToDeg(2 * Math.acos(half.w))).toFixed(1), 'degrees');
console.log('angle between identity and yaw:', THREE.MathUtils.radToDeg(new THREE.Quaternion().angleTo(yaw)).toFixed(1), 'degrees');
</script>premultiply(b) means "after what I already am, also apply b", matching the model's mul(pitch90, yaw90). multiply(b) is the opposite, this × b: it applies b first, in the object's local frame. That is the quaternion version of "rotate around my own axis" (rotateY) vs "around the world axis".
lookAt: face a point
object.lookAt(x, y, z) (or a Vector3) rotates an object to face a world-space point, keeping its "up" toward object.up (default +Y). One detail trips everybody: cameras and lights look down their −Z axis, every other object points its +Z axis at the target. glTF characters face +Z, so enemy.lookAt(player.position) makes them face the player, and camera.lookAt(player.position) aims the camera at the player.
Instant lookAt snaps. To turn smoothly, compute the target rotation and move toward it a limited angle per second with rotateTowards:
<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('#171c29');
const camera = new THREE.PerspectiveCamera(45, innerWidth / innerHeight, 0.1, 100);
camera.position.set(0, 9, 9);
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(16, 16, '#445', '#2a3040'));
// A "guard": a cone whose tip points along local +Z, like a glTF model's front.
function guard(x, color) {
const g = new THREE.Group();
const body = new THREE.Mesh(new THREE.CylinderGeometry(0.4, 0.4, 0.8, 20), new THREE.MeshStandardMaterial({ color }));
body.position.y = 0.4;
const nose = new THREE.Mesh(new THREE.ConeGeometry(0.25, 0.8, 16), new THREE.MeshStandardMaterial({ color: '#eeeeee' }));
nose.rotation.x = Math.PI / 2; // cone tip from +Y to +Z
nose.position.set(0, 0.5, 0.6);
g.add(body, nose);
g.position.x = x;
scene.add(g);
return g;
}
const snapper = guard(-2.5, '#e57373'); // uses lookAt every frame
const turner = guard(2.5, '#64b5f6'); // turns at most 90° per second
const target = new THREE.Mesh(new THREE.SphereGeometry(0.3, 20, 10), new THREE.MeshStandardMaterial({ color: '#ffd54f', emissive: '#806010' }));
target.position.y = 0.4;
scene.add(target);
const helper = new THREE.Object3D(); // used to compute the wanted rotation
const wanted = new THREE.Quaternion();
const timer = new THREE.Timer();
renderer.setAnimationLoop((t) => {
timer.update(t);
const dt = Math.min(timer.getDelta(), 0.1), time = Math.max(0, timer.getElapsed());
// The target jumps between waypoints every 1.5 s, so the difference is easy to see.
const k = Math.floor(time / 1.5) % 4;
target.position.x = [0, 5, 0, -5][k];
target.position.z = [5, 0, -5, 0][k];
snapper.lookAt(target.position.x, 0, target.position.z);
helper.position.copy(turner.position);
helper.lookAt(target.position.x, 0, target.position.z);
wanted.copy(helper.quaternion);
turner.quaternion.rotateTowards(wanted, THREE.MathUtils.degToRad(90) * dt);
renderer.render(scene, camera);
});
</script>The red guard snaps; the blue one turns at a fixed 90°/s, which reads as "alive". For guards and turrets, a turn-rate limit is also a gameplay value: a slow turret gives the player a chance. (Look at the target's position at your own height, y = 0 here, or the guard tips over to look up or down at it.)
When to use what
| Situation | Use |
|---|---|
| Editor values, a single axis (turret yaw, door) | rotation (Euler) |
| First-person camera | Euler with order = 'YXZ': yaw on Y, clamped pitch on X |
| Smooth turning, aiming, AI facing | lookAt on a helper + rotateTowards or slerp |
| Physics bodies, animation clips, networking | quaternions (that is what engines, glTF and the mixer store) |
| Combining rotations | multiply (local) / premultiply (world) |
Tip:
q.slerp(target, 0.1)every frame is an exponential ease, and frame-rate dependent. Use1 - Math.exp(-speed * dt)as the factor, orrotateTowardswithrate * dtfor a constant turn speed.
Test yourself
You call enemy.lookAt(player.position) on a glTF character and on the camera. Which local axis ends up pointing at the player in each case?
- −Z for both
- +Z for the enemy, −Z for the camera
- +Y for both
- +X for the enemy, −Z for the camera
Why does a 90° rotation around Y have w ≈ 0.707 instead of w = 0?
- Rounding error
- Quaternions store half the angle: w = cos(45°)
- Three.js normalises to 0.707
- Because Y is the up axis
Which call turns an object toward a target rotation at a constant speed of 120°/s?
q.slerp(target, 120)q.rotateTowards(target, THREE.MathUtils.degToRad(120) * dt)q.multiply(target)object.lookAt(target)