Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 39 ยท Scene, Camera and Renderer

Vectors, Matrices and Quaternions

Learn the Three.js math classes: Vector3 operations, dot and cross products, Matrix4 transforms, quaternions and slerp, plus MathUtils helpers with live demos.

Three.js includes a compact math library, and you will use it in almost every project: to move things, aim things, measure distances and blend orientations. You do not need to be a mathematician. You need to know what each class is for and a handful of methods. This lesson covers Vector3, Matrix4, Quaternion, Euler and MathUtils.

Vector3

A Vector3 holds x, y and z. It represents a position, a direction or a size, depending on context. Most methods modify the vector in place and return it, so you can chain calls. Use clone() when you need a copy.

JavaScript
const a = new THREE.Vector3(1, 2, 3);
const b = new THREE.Vector3(4, 0, 1);

a.add(b);                    // a = a + b
a.sub(b);                    // a = a - b
a.multiplyScalar(2);         // scale
a.length();                  // magnitude
a.normalize();               // same direction, length 1
a.distanceTo(b);             // distance between two points
a.lerp(b, 0.25);             // move 25% of the way toward b
a.clone().sub(b);            // a new vector, a unchanged

Mind the in-place behavior: const dir = target.position.sub(player.position) changes the target's position! The safe form is target.position.clone().sub(player.position). Creating new vectors every frame also creates garbage for the collector, so in hot loops reuse a few vectors declared outside the loop.

Dot and cross product

  • a.dot(b) returns a number. For unit vectors it is the cosine of the angle between them: 1 means the same direction, 0 perpendicular, -1 opposite. Use it to test "is that enemy in front of me?" or to compute diffuse lighting.
  • a.cross(b) returns a vector perpendicular to both. Use it to compute a surface normal from two edges, or to find a "right" vector from "forward" and "up".
JavaScript
const forward = new THREE.Vector3(0, 0, -1);
const toTarget = target.clone().sub(me).normalize();
const infront = forward.dot(toTarget) > 0.5; // within about 60 degrees

Euler and Quaternion

Euler angles are three numbers and easy to understand. Quaternions are four numbers that represent a rotation without gimbal lock and interpolate smoothly. Every Object3D keeps both in sync: object.rotation (Euler) and object.quaternion. Changing one updates the other.

JavaScript
const q = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 1, 0), Math.PI / 2);
mesh.quaternion.copy(q);

mesh.quaternion.slerp(targetQuaternion, 0.1); // smooth turn toward another orientation
mesh.lookAt(target);                          // meshes aim +Z at it; cameras and lights aim -Z

slerp (spherical linear interpolation) blends two orientations along the shortest arc at constant speed. It is how you rotate smoothly from one pose to another, which Euler angles cannot do reliably.

Quaternion slerp

setFromUnitVectors(from, to) builds the rotation that turns one direction into another, which is perfect for aiming things whose model points along an axis other than -Z.

Matrix4

A Matrix4 is a 4x4 grid of numbers that packs position, rotation and scale into one object. The GPU works with matrices. You rarely build them by hand, but knowing the roles helps:

  • object.matrix is the local transform (built from position, quaternion, scale).
  • object.matrixWorld is the transform in world space, including parents.
  • camera.matrixWorldInverse is the view matrix; camera.projectionMatrix applies perspective.

Three.js updates these automatically before each render (matrixAutoUpdate). If you change something and need the result right away, call object.updateMatrixWorld(true).

JavaScript
const m = new THREE.Matrix4().compose(position, quaternion, scale);
m.decompose(pos, quat, scl);         // the reverse
const inverse = m.clone().invert();
const worldPoint = localPoint.clone().applyMatrix4(object.matrixWorld);
const localPoint2 = worldPoint.clone().applyMatrix4(object.matrixWorld.clone().invert());

object.localToWorld(v) and object.worldToLocal(v) do those last two conversions for you.

Projecting a 3D point to the screen

A common need is to place an HTML label next to a 3D object. vector.project(camera) converts a world point into normalized device coordinates, where x and y run from -1 to 1; then you map those to pixels.

HTML label that follows a 3D point

The reverse direction, from a mouse position to a ray in 3D, uses Raycaster and appears in the interaction chapter.

MathUtils

THREE.MathUtils collects small helpers that prevent repeated code:

Function Meaning
degToRad(d), radToDeg(r) Convert angles
clamp(v, min, max) Limit a value
lerp(a, b, t) Blend two numbers
mapLinear(x, a1, a2, b1, b2) Remap a range
smoothstep(x, min, max) Smooth 0 to 1 ramp
randFloat(min, max), randInt(min, max), randFloatSpread(range) Random numbers
damp(x, y, lambda, dt) Frame-rate independent smoothing
Vector and matrix sanity checks

Check the third-to-last line by hand: rotating (1,0,0) by 90 degrees about y gives (0,0,-1), scaling by 2 gives (0,0,-2), and adding the translation (5,0,0) gives (5,0,-2).

Vector methods mutate. If a position changes unexpectedly, look for a missing clone() first.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a.sub(b) do to a?

    Most Vector3 methods mutate the vector. Clone first when you need the original.
  2. 2. For two unit vectors, what does a dot product of 0 mean?

    The dot product of unit vectors is the cosine of the angle: 1, 0 and -1 for 0, 90 and 180 degrees.
  3. 3. Why prefer quaternions for smooth rotation between two orientations?

    Interpolating Euler angles can twist strangely. Quaternion slerp is smooth and constant speed.
  4. 4. What does vector.project(camera) return?

    Map the x and y values to pixels yourself, and check z to see if the point is in front of the camera.

Summary

  • Vector3 methods mutate in place; clone() first and reuse vectors in hot loops.
  • Dot gives alignment, cross gives a perpendicular; both are everywhere in 3D code.
  • Quaternions rotate and interpolate without gimbal lock; object.rotation and object.quaternion stay in sync.
  • Matrix4 stores a full transform; localToWorld, worldToLocal and project(camera) convert between spaces.
  • MathUtils provides degToRad, clamp, lerp, damp and friends.

Next: Built-in Geometries