Once you've brought your animations to life with Three.js, the next logical step is to give your users control over how and when those animations play. This section will explore the fundamental methods for managing animation playback, allowing you to create interactive and dynamic 3D experiences. We'll cover how to start, stop, pause, and even loop your animations, giving you granular control over the user's journey within your 3D scene.
Three.js provides a straightforward API for controlling animation playback through the AnimationMixer object. Remember that the AnimationMixer is responsible for playing back animations associated with a specific Object3D, such as a loaded glTF model. Each Object3D that has animations will typically have its own AnimationMixer.
To begin with, let's recall how you typically get an AnimationMixer and an animation action. You'll usually load a model, find its animations, and then create an action from one of those animations using the mixer.
const mixer = new THREE.AnimationMixer(model);
const clips = model.animations;
const action = mixer.clipAction(clips[0]);Now, let's dive into controlling the playback of these actions.
The most basic control is to start an animation. The play() method on an AnimationAction object begins playback. If the animation is already playing, calling play() again will typically restart it from the beginning. By default, animations will play once and then stop.
action.play();When you want to temporarily halt an animation, the pause() method is your go-to. It freezes the animation at its current frame. When you later call play() again, the animation will resume from where it was paused. This is useful for interactive scenarios where you might want to pause a character's animation while the user performs an action.