Three.js アニメーション
使用するタイミング
- Three.js でオブジェクト、リグ、モーフターゲット、またはインポートした GLTF アニメーションをアニメーションさせる必要がある場合。
- タスクがミキサー、クリップ、キーフレーム、プロシージャルモーション、またはアニメーションブレンドに関連する場合。
- 静的なレンダリングだけでなく、Three.js シーンでモーション動作を構築している場合。
クイックスタート
import * as THREE from "three";
// Timer を使ったシンプルなプロシージャルアニメーション(r183 推奨)
const timer = new THREE.Timer();
renderer.setAnimationLoop(() => {
timer.update();
const delta = timer.getDelta();
const elapsed = timer.getElapsed();
mesh.rotation.y += delta;
mesh.position.y = Math.sin(elapsed) * 0.5;
renderer.render(scene, camera);
});
注: r183 以降は THREE.Clock よりも THREE.Timer が推奨されています。Timer はページが非表示のときに一時停止し、よりクリーンな API を提供します。THREE.Clock も引き続き動作しますが、レガシーと見なされます。
アニメーションシステムの概要
Three.js アニメーションシステムには、以下の 3 つの主要コンポーネントがあります。
- AnimationClip - キーフレームデータのコンテナ
- AnimationMixer - ルートオブジェクトでアニメーションを再生
- AnimationAction - クリップの再生を制御
AnimationClip
キーフレームアニメーションデータを保存します。
// アニメーションクリップの作成
const times = [0, 1, 2]; // キーフレームの時間(秒)
const values = [0, 1, 0]; // 各キーフレームでの値
const track = new THREE.NumberKeyframeTrack(
".position[y]", // プロパティパス
times,
values,
);
const clip = new THREE.AnimationClip("bounce", 2, [track]);
KeyframeTrack の種類
// 数値トラック(単一値)
new THREE.NumberKeyframeTrack(".opacity", times, [1, 0]);
new THREE.NumberKeyframeTrack(".material.opacity", times, [1, 0]);
// ベクトルトラック(位置、スケール)
new THREE.VectorKeyframeTrack(".position", times, [
0,
0,
0, // t=0
1,
2,
0, // t=1
0,
0,
0, // t=2
]);
// クォータニオントラック(回転)
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],
);
// カラートラック
new THREE.ColorKeyframeTrack(".material.color", times, [
1,
0,
0, // 赤
0,
1,
0, // 緑
0,
0,
1, // 青
]);
// ブーリアントラック
new THREE.BooleanKeyframeTrack(".visible", [0, 0.5, 1], [true, false, true]);
// 文字列トラック(モーフターゲット用)
new THREE.StringKeyframeTrack(
".morphTargetInfluences[smile]",
[0, 1],
["0", "1"],
);
補間モード
const track = new THREE.VectorKeyframeTrack(".position", times, values);
// 補間
const track = new THREE.VectorKeyframeTrack(".position", times, values);
track.setInterpolation(THREE.InterpolateLinear); // デフォルト
track.setInterpolation(THREE.InterpolateSmooth); // 3 次スプライン
track.setInterpolation(THREE.InterpolateDiscrete); // ステップ関数
BezierInterpolant(r183)
Three.js r183 では、キーフレームトラックのベジエ曲線補間のための THREE.BezierInterpolant が追加され、接線制御によるより滑らかなアニメーションカーブが可能になりました。
AnimationMixer
オブジェクトとその子孫でアニメーションを再生します。
const mixer = new THREE.AnimationMixer(model);
// クリップからアクションを作成
const action = mixer.clipAction(clip);
action.play();
// アニメーションループで更新
function animate() {
const delta = clock.getDelta();
mixer.update(delta); // 必須!
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
ミキサーイベント
mixer.addEventListener("finished", (e) => {
console.log("Animation finished:", e.action.getClip().name);
});
mixer.addEventListener("loop", (e) => {
console.log("Animation looped:", e.action.getClip().name);
});
AnimationAction
アニメーションクリップの再生を制御します。
const action = mixer.clipAction(clip);
// 再生制御
action.play();
action.stop();
action.reset();
action.halt(fadeOutDuration);
// 再生状態
action.isRunning();
action.isScheduled();
// 時間制御
action.time = 0.5; // 現在の時間
action.timeScale = 1; // 再生速度(負の値 = 逆再生)
action.paused = false;
// ウェイト(ブレンド用)
action.weight = 1; // 0~1、最終ポーズへの寄与度
action.setEffectiveWeight(1);
// ループモード
action.loop = THREE.LoopRepeat; // デフォルト: 無限ループ
action.loop = THREE.LoopOnce; // 1 回再生して停止
action.loop = THREE.LoopPingPong; // 順方向/逆方向を交互に繰り返す
action.repetitions = 3; // ループ回数(デフォルトは Infinity)
// クランプ
action.clampWhenFinished = true; // 終了時に最後のフレームを保持
// ブレンド
action.blendMode = THREE.NormalAnimationBlendMode;
action.blendMode = THREE.AdditiveAnimationBlendMode;
フェードイン/アウト
// フェードイン
action.reset().fadeIn(0.5).play();
// フェードアウト
action.fadeOut(0.5);
// アニメーション間のクロスフェード
const action1 = mixer.clipAction(clip1);
const action2 = mixer.clipAction(clip2);
action1.play();
// 後で、action2 にクロスフェード
action1.crossFadeTo(action2, 0.5, true);
action2.play();
GLTF アニメーションの読み込み
スケルタルアニメーションの最も一般的なソースです。
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
const loader = new GLTFLoader();
loader.load("model.glb", (gltf) => {
const model = gltf.scene;
scene.add(model);
// ミキサーの作成
const mixer = new THREE.AnimationMixer(model);
// すべてのクリップを取得
const clips = gltf.animations;
console.log(
"Available animations:",
clips.map((c) => c.name),
);
// 最初のアニメーションを再生
if (clips.length > 0) {
const action = mixer.clipAction(clips[0]);
action.play();
}
// 名前で特定のアニメーションを再生
const walkClip = THREE.AnimationClip.findByName(clips, "Walk");
if (walkClip) {
mixer.clipAction(walkClip).play();
}
// 更新ループ用にミキサーを保存
window.mixer = mixer;
});
// アニメーションループ
function animate() {
const delta = clock.getDelta();
if (window.mixer) window.mixer.update(delta);
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
スケルタルアニメーション
スケルトンとボーン
// スキンメッシュからスケルトンにアクセス
const skinnedMesh = model.getObjectByProperty("type", "SkinnedMesh");
const skeleton = skinnedMesh.skeleton;
// ボーンにアクセス
skeleton.bones.forEach((bone) => {
console.log(bone.name, bone.position, bone.rotation);
});
// 名前で特定のボーンを見つける
const headBone = skeleton.bones.find((b) => b.name === "Head");
if (headBone) headBone.rotation.y = Math.PI / 4; // 頭を回す
// スケルトンヘルパー
const helper = new THREE.SkeletonHelper(model);
scene.add(helper);
プログラムによるボーンアニメーション
function animate() {
const time = clock.getElapsedTime();
// ボーンをアニメーション
const headBone = skeleton.bones.find((b) => b.name === "Head");
if (headBone) {
headBone.rotation.y = Math.sin(time) * 0.3;
}
// クリップも再生している場合はミキサーを更新
mixer.update(clock.getDelta());
}
ボーンへのアタッチメント
// オブジェクトをボーンにアタッチ
const weapon = new THREE.Mesh(weaponGeometry, weaponMaterial);
const handBone = skeleton.bones.find((b) => b.name === "RightHand");
if (handBone) handBone.add(weapon);
// アタッチメントのオフセット
weapon.position.set(0, 0, 0.5);
weapon.rotation.set(0, Math.PI / 2, 0);
モーフターゲット
異なるメッシュ形状をブレンドします。
// モーフターゲットはジオメトリに保存される
const geometry = mesh.geometry;
console.log("Morph attributes:", Object.keys(geometry.morphAttributes));
// モーフターゲットの影響にアクセス
mesh.morphTargetInfluences; // ウェイトの配列
mesh.morphTargetDictionary; // 名前 -> インデックスのマッピング
// インデックスでモーフターゲットを設定
mesh.morphTargetInfluences[0] = 0.5;
// 名前で設定
const smileIndex = mesh.morphTargetDictionary["smile"];
mesh.morphTargetInfluences[smileIndex] = 1;
モーフターゲットのアニメーション
// プロシージャル
function animate() {
const t = clock.getElapsedTime();
mesh.morphTargetInfluences[0] = (Math.sin(t) + 1) / 2;
}
// キーフレームアニメーションを使用
const track = new THREE.NumberKeyframeTrack(
".morphTargetInfluences[smile]",
[0, 0.5, 1],
[0, 1, 0],
);
const clip = new THREE.AnimationClip("smile", 1, [track]);
mixer.clipAction(clip).play();
アニメーションブレンド
複数のアニメーションを混ぜ合わせます。
// アクションのセットアップ
const idleAction = mixer.clipAction(idleClip);
const walkAction = mixer.clipAction(walkClip);
const runAction = mixer.clipAction(runClip);
// 異なるウェイトですべてを再生
idleAction.play();
walkAction.play();
runAction.play();
// 初期ウェイトを設定
idleAction.setEffectiveWeight(1);
walkAction.setEffectiveWeight(0);
runAction.setEffectiveWeight(0);
// 速度に基づいてブレンド
function updateAnimations(speed) {
if (speed < 0.1) {
idleAction.setEffectiveWeight(1);
walkAction.setEffectiveWeight(0);
runAction.setEffectiveWeight(0);
} else if (speed < 5) {
const t = speed / 5;
idleAction.setEffectiveWeight(1 - t);
walkAction.setEffectiveWeight(t);
runAction.setEffectiveWeight(0);
} else {
const t = Math.min((speed - 5) / 5, 1);
idleAction.setEffectiveWeight(0);
walkAction.setEffectiveWeight(1 - t);
runAction.setEffectiveWeight(t);
}
}
加算ブレンド
// ベースポーズ
const baseAction = mixer.clipAction(baseClip);
baseAction.play();
// 加算レイヤー(例: 呼吸)
const additiveAction = mixer.clipAction(additiveClip);
additiveAction.blendMode = THREE.AdditiveAnimationBlendMode;
additiveAction.play();
// クリップを加算に変換
THREE.AnimationUtils.makeClipAdditive(additiveClip);
アニメーションユーティリティ
import * as THREE from "three";
// 名前でクリップを検索
const clip = THREE.AnimationClip.findByName(clips, "Walk");
// サブクリップを作成
const subclip = THREE.AnimationUtils.subclip(clip, "subclip", 0, 30, 30);
// 加算に変換
THREE.AnimationUtils.makeClipAdditive(clip);
THREE.AnimationUtils.makeClipAdditive(clip, 0, referenceClip);
// クリップを複製
const clone = clip.clone();
// クリップの長さを取得
clip.duration;
// クリップを最適化(冗長なキーフレームを削除)
clip.optimize();
// クリップを最初のフレームにリセット
clip.resetDuration();
プロシージャルアニメーションパターン
スムーズダンピング
// スムーズフォロー/lerp
const target = new THREE.Vector3();
const current = new THREE.Vector3();
const velocity = new THREE.Vector3();
function smoothDamp(current, target, velocity, smoothTime, deltaTime) {
const omega = 2 / smoothTime;
const x = omega * deltaTime;
const exp = 1 / (1 + x + 0.48 * x * x + 0.235 * x * x * x);
const change = current.clone().sub(target);
const temp = velocity
.clone()
.add(change.clone().multiplyScalar(omega))
.multiplyScalar(deltaTime);
velocity.sub(temp.clone().multiplyScalar(omega)).multiplyScalar(exp);
return target.clone().add(change.add(temp).multiplyScalar(exp));
}
function animate() {
current.copy(smoothDamp(current, target, velocity, 0.3, delta));
mesh.position.copy(current);
}
ばね物理
class Spring {
constructor(stiffness = 100, damping = 10) {
this.stiffness = stiffness;
this.damping = damping;
this.position = 0;
this.velocity = 0;
this.target = 0;
}
update(dt) {
const force = -this.stiffness * (this.position - this.target);
const dampingForce = -this.damping * this.velocity;
this.velocity += (force + dampingForce) * dt;
this.position += this.velocity * dt;
return this.position;
}
}
const spring = new Spring(100, 10);
spring.target = 1;
function animate() {
mesh.position.y = spring.update(delta);
}
振動
function animate() {
const t = clock.getElapsedTime();
// サイン波
mesh.position.y = Math.sin(t * 2) * 0.5;
// バウンド
mesh.position.y = Math.abs(Math.sin(t * 3)) * 2;
// 円運動
mesh.position.x = Math.cos(t) * 2;
mesh.position.z = Math.sin(t) * 2;
// 8 の字
mesh.position.x = Math.sin(t) * 2;
mesh.position.z = Math.sin(t * 2) * 1;
}
パフォーマンスのヒント
- クリップを共有: 同じ AnimationClip を複数のミキサーで使用できます
- クリップを最適化:
clip.optimize()を呼び出して冗長なキーフレームを削除 - 画面外では無効化: 非表示オブジェクトのミキサー更新を停止
- アニメーションに LOD を使用: 遠くのキャラクターには簡略化されたリグを使用
- アクティブなミキサーを制限: 各 mixer.update() にはコストがかかります
// 非表示時にアニメーションを一時停止
mesh.onBeforeRender = () => {
action.paused = false;
};
mesh.onAfterRender = () => {
// 次のフレームで表示されるかチェック
if (!isInFrustum(mesh)) {
action.paused = true;
}
};
// クリップをキャッシュ
const clipCache = new Map();
function getClip(name) {
if (!clipCache.has(name)) {
clipCache.set(name, loadClip(name));
}
return clipCache.get(name);
}
関連項目
threejs-loaders- アニメーション付き GLTF モデルの読み込みthreejs-fundamentals- クロックとアニメーションループthreejs-shaders- シェーダーでの頂点アニメーション
制限事項
- このスキルは、タスクが上記の範囲に明確に一致する場合にのみ使用してください。
- 出力を、環境固有の検証、テスト、または専門家によるレビューの代わりとして扱わないでください。
- 必要な入力、権限、安全境界、または成功基準が欠落している場合は、立ち止まって明確化を求めてください。