Now that we've got our 3D scene set up and some objects within it, the next exciting step is to bring them to life! Animation is what transforms static renders into dynamic and engaging experiences. In Three.js, animating an object primarily involves changing its properties over time. The most common properties we'll animate are its position, rotation, and scale.
The core of animation in Three.js, and indeed in most game engines or 3D frameworks, relies on a game loop or render loop. This loop continuously updates the scene and redraws it on the screen. For each frame of the animation, we'll calculate new values for our object's properties and update them before rendering. Three.js provides the requestAnimationFrame API, which is the standard way to handle this loop in web browsers. It's efficient because it pauses animation when the tab is inactive, saving resources.
function animate() {
requestAnimationFrame(animate);
// Update object properties here
renderer.render(scene, camera);
}
animate();Let's break down how to animate each of these fundamental properties: position, rotation, and scale.
Animating Position
To move an object, we modify its position property, which is a Vector3 object. This object has x, y, and z components. By incrementally changing these values within our animation loop, we can make the object move along any axis or a combination of axes.
const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
function animate() {
requestAnimationFrame(animate);
// Move the cube along the X-axis
cube.position.x += 0.01;
renderer.render(scene, camera);
}In this example, the cube's x position increases by 0.01 in each frame, causing it to move to the right. You can achieve more complex movements by animating y and z as well, or by introducing mathematical functions to control the speed and direction of movement.