Loop Three.js Animation a Specific Number of Times
Controlling the repetition of animations in Three.js is crucial for
creating precise interactive 3D experiences. This guide explains how to
configure the AnimationMixer and
AnimationAction to loop a specific animation a set number
of times rather than playing it infinitely, complete with practical code
examples.
To limit the number of times an animation plays in Three.js, you must
configure the AnimationAction object returned by your
AnimationMixer. This is achieved using the
setLoop method.
Step-by-Step Implementation
- Get the AnimationAction: Create an action from your mixer using your animation clip.
- Configure the Loop Mode: Call
setLoopon the action, passingTHREE.LoopRepeat(orTHREE.LoopPingPong) as the first argument, and your desired repetition count as the second argument. - Play the Animation: Call the
play()method.
Here is the essential code to loop an animation exactly 3 times:
import * as THREE from 'three';
// 1. Initialize the mixer and get the action
const mixer = new THREE.AnimationMixer(myMesh);
const action = mixer.clipAction(myAnimationClip);
// 2. Set the loop mode and the number of repetitions (e.g., 3 times)
action.setLoop(THREE.LoopRepeat, 3);
// Optional: Keep the mesh at the last frame when finished
action.clampWhenFinished = true;
// 3. Play the animation
action.play();Understanding the Parameters
The setLoop method accepts two parameters:
mode(constant): Controls how the animation loops.THREE.LoopRepeat: Plays the animation from start to finish, then jumps back to the start.THREE.LoopPingPong: Plays the animation forward, then backward, alternating directions.
repetitions(number): The exact number of times the animation will play. By default, this is set toInfinity. Setting it to an integer like3or5will stop the animation after that many cycles.
Handling the Finished Event
If you want to trigger an action (such as loading a new animation or
UI change) after the loop finishes, you can listen to the mixer’s
finished event:
mixer.addEventListener('finished', (event) => {
if (event.action === action) {
console.log("Animation completed its specified loops.");
// Add your custom logic here
}
});