Translate Object on Local Axis in Three.js
Moving objects in 3D space is a fundamental task in Three.js, but
default position updates occur relative to the world coordinate system.
This article provides a straightforward guide on how to translate a 3D
object along its own local axis, accounting for its current rotation,
using the built-in Three.js methods translateOnAxis,
translateX, translateY, and
translateZ.
The Shorthand Translation Methods
The simplest way to move an object along its local X, Y, or Z axis is
by using the dedicated translation methods. Unlike modifying the
object.position property directly, which moves the object
along the world axes, these methods automatically calculate the object’s
current orientation.
// Move the object 5 units along its local X-axis
mesh.translateX(5);
// Move the object 2 units along its local Y-axis
mesh.translateY(2);
// Move the object -3 units along its local Z-axis
mesh.translateZ(-3);Whenever these methods are called, Three.js internally determines the object’s direction based on its rotation matrix and applies the movement relative to that orientation.
Translating Along a Custom Local Axis
If you need to move an object along an arbitrary local direction
rather than the standard X, Y, or Z axes, use the
translateOnAxis method. This method requires a normalized
direction vector (a vector with a length of 1) and the distance you want
to move.
import * as THREE from 'three';
// Define a custom local direction vector (e.g., diagonally up and right)
const localDirection = new THREE.Vector3(1, 1, 0);
// Normalize the vector to ensure accurate distance calculation
localDirection.normalize();
const distance = 5;
// Translate the object along this custom local axis
mesh.translateOnAxis(localDirection, distance);Local Translation vs. Position Modification
Understanding the difference between direct position modification and local translation is crucial for correct movement behavior in 3D scenes:
- Direct Modification
(
mesh.position.x += 5): Moves the object along the world’s X-axis (or its parent’s X-axis if nested). If the object is rotated 90 degrees, it will still slide along the global X-axis. - Local Translation
(
mesh.translateX(5)): Moves the object along its own X-axis. If the object is rotated 90 degrees, it will move in the direction that its “right side” is currently facing relative to the world.