Rotation, scaling, and position updates

Back to Modules

Object Transformations: Position, Rotation, and Scaling in Three.js

In Three.js, manipulating objects in a 3D scene involves transforming them through changes in their position, rotation, and scaling. These transformations are managed through the Object3D class, which is the base class for most objects in Three.js, including Mesh, Camera, and Light objects.

Position

The position property of an Object3D instance is a Vector3 object. It represents the object's local position relative to its parent object. You can modify the position by directly setting its x, y, and z components or by using Vector3 methods like set(), setX(), setY(), setZ(), or copy().

mesh.position.x = 5; // Move 5 units along the X-axis
mesh.position.set(1, 2, 3); // Set X, Y, and Z coordinates

Rotation

The rotation property of an Object3D is an Euler angle instance, representing rotations around the X, Y, and Z axes in radians. You can set individual axis rotations or use the set() method. Three.js also uses Quaternion objects for rotation, which can help avoid issues like Gimbal Lock that can occur with Euler angles. The lookAt() method is a convenient way to orient an object to face a specific point in space.

object.rotation.y += 0.01; // Rotate around the Y-axis
object.rotation.set(Math.PI / 2, 0, 0); // Set rotation to 90 degrees around X-axis
object.lookAt(new THREE.Vector3(0, 0, 0)); // Make the object look at the origin

Scaling

The scale property of an Object3D is also a Vector3 object. By default, the scale vector is (1, 1, 1), meaning no scaling is applied. Setting values less than 1 will make the object smaller, while values greater than 1 will make it larger. You can scale uniformly by setting all three components to the same value or non-uniformly by assigning different values to x, y, and z.

object.scale.set(2, 2, 2); // Scale uniformly by 2
object.scale.y = 0.5; // Scale only along the Y-axis by 0.5

Example: Object Transformations

This example demonstrates how to change the position, rotation, and scale of a cube in a Three.js scene.