Animation Three.js
Démarrage rapide
import * as THREE from "three";
// Animation procédurale simple
const clock = new THREE.Clock();
function animate() {
const delta = clock.getDelta();
const elapsed = clock.getElapsedTime();
mesh.rotation.y += delta;
mesh.position.y = Math.sin(elapsed) * 0.5;
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
animate();
Présentation du système d'animation
Le système d'animation de Three.js comporte trois composants principaux :
- AnimationClip - Conteneur pour les données d'images clés
- AnimationMixer - Joue des animations sur un objet racine
- AnimationAction - Contrôle la lecture d'un clip
AnimationClip
Stocke les données d'animation par images clés.
// Créer un clip d'animation
const times = [0, 1, 2]; // Temps des images clés (secondes)
const values = [0, 1, 0]; // Valeurs à chaque image clé
const track = new THREE.NumberKeyframeTrack(
".position[y]", // Chemin de la propriété
times,
values,
);
const clip = new THREE.AnimationClip("bounce", 2, [track]);
Types de KeyframeTrack
// Piste numérique (valeur unique)
new THREE.NumberKeyframeTrack(".opacity", times, [1, 0]);
new THREE.NumberKeyframeTrack(".material.opacity", times, [1, 0]);
// Piste vectorielle (position, échelle)
new THREE.VectorKeyframeTrack(".position", times, [
0,
0,
0, // t=0
1,
2,
0, // t=1
0,
0,
0, // t=2
]);
// Piste de quaternion (rotation)
const q1 = new THREE.Quaternion().setFromEuler(new THREE.Euler(0, 0, 0));
const q2 = new THREE.Quaternion().setFromEuler(new THREE.Euler(0, Math.PI, 0));
new THREE.QuaternionKeyframeTrack(
".quaternion",
[0, 1],
[q1.x, q1.y, q1.z, q1.w, q2.x, q2.y, q2.z, q2.w],
);
// Piste de couleur
new THREE.ColorKeyframeTrack(".material.color", times, [
1,
0,
0, // rouge
0,
1,
0, // vert
0,
0,
1, // bleu
]);
// Piste booléenne
new THREE.BooleanKeyframeTrack(".visible", [0, 0.5, 1], [true, false, true]);
// Piste de chaîne (pour les cibles de morphing)
new THREE.StringKeyframeTrack(
".morphTargetInfluences[smile]",
[0, 1],
["0", "1"],
);
Modes d'interpolation
const track = new THREE.VectorKeyframeTrack(".position", times, values);
// Interpolation
track.setInterpolation(THREE.InterpolateLinear); // Par défaut
track.setInterpolation(THREE.InterpolateSmooth); // Spline cubique
track.setInterpolation(THREE.InterpolateDiscrete); // Fonction échelon
AnimationMixer
Joue des animations sur un objet et ses descendants.
const mixer = new THREE.AnimationMixer(model);
// Créer une action à partir d'un clip
const action = mixer.clipAction(clip);
action.play();
// Mettre à jour dans la boucle d'animation
function animate() {
const delta = clock.getDelta();
mixer.update(delta); // Obligatoire !
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
Événements du Mixer
mixer.addEventListener("finished", (e) => {
console.log(\