Communitygithub.com

BEKO2210/Firstbrain

Three.js アニメーション - キーフレームアニメーション、スケルタルアニメーション、モーフターゲット、アニメーションブレンド。オブジェクトのアニメーション、GLTFアニメーションの再生、プロシージャルモーションの作成、アニメーションのブレンドに使用します。

Firstbrain とは?

このスキルは、Three.jsのアニメーションシステムを包括的にカバーしています。主な機能として、AnimationClipを使用したキーフレームアニメーションの作成、AnimationMixerによるアニメーションの再生・ブレンド、AnimationActionによる再生制御(再生・停止・フェード・クロスフェード)を提供します。さらに、GLTFモデルから読み込んだスケルタルアニメーションの操作、モーフターゲットによる形状変化のアニメーション、複数アニメーションの重み付けブレンドや加算ブレンドといった高度なブレンド技法をサポートしています。プロシージャルアニメーションのパターンとして、スムーズダンピング、ばね物理、振動運動などの実装例も含まれており、パフォーマンス最適化のヒントも提供します。このスキルはClaude Code, Cursor, CodexなどのAIエージェントがThree.jsシーンに動きを追加する際に活用できます。

対応~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/BEKO2210/Firstbrain/tree/HEAD/03%20-%20Resources/Skills/threejs-animation

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

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.Timer は THREE.Clock よりも推奨されています。Timerはページが非表示のときに一時停止し、よりクリーンなAPIを提供します。THREE.Clock は引き続き使用できますが、レガシーと見なされます。

アニメーションシステムの概要

Three.jsアニメーションシステムは3つの主要コンポーネントで構成されています:

  1. AnimationClip - キーフレームデータのコンテナ
  2. AnimationMixer - ルートオブジェクトでアニメーションを再生
  3. 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 interpolation = 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("アニメーション終了:", e.action.getClip().name);
});

mixer.addEventListener("loop", (e) => {
  console.log("アニメーションループ:", 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(
    "利用可能なアニメーション:",
    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("モーフ属性:", 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;
}

パフォーマンスのヒント

  1. クリップを共有: 同じAnimationClipを複数のミキサーで使用できます
  2. クリップを最適化: clip.optimize() で冗長なキーフレームを削除します
  3. 画面外では無効化: 非表示オブジェクトのミキサー更新を停止します
  4. アニメーションにLODを使用: 遠くのキャラクターには簡易リグを使用します
  5. アクティブなミキサーを制限: 各 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 - シェーダーでの頂点アニメーション

接続

  • ドメイン: [[Design & Kreativitaet]]
  • カテゴリ: [[3D & Animation]]
  • ナビゲーション: [[Skills Uebersicht]], [[Home]]

Individual skills in this repo

This repo contains 18 individual skills — each has its own dedicated page.

BEKO2210/Firstbrain

Skill for discovering and researching autonomous AI agents, tools, and ecosystems using the AgentFolio directory.

BEKO2210/Firstbrain

Advanced JavaScript animation library skill for creating complex, high-performance web animations.

BEKO2210/Firstbrain

One sentence - what this skill does and when to invoke it

BEKO2210/Firstbrain

Audit and fix animation performance issues including layout thrashing, compositor properties, scroll-linked motion, and blur effects. Use when animations stutter, transitions jank, or reviewing CSS/JS animation performance.

BEKO2210/Firstbrain

Internationalization and localization patterns. Detecting hardcoded strings, managing translations, locale files, RTL support.

BEKO2210/Firstbrain

Expert in building portfolios that actually land jobs and clients -

BEKO2210/Firstbrain

Generates high-converting Next.js/React landing pages with Tailwind CSS. Uses PAS, AIDA, and BAB frameworks for optimized copy/components (Heroes, Features, Pricing). Focuses on Core Web Vitals/SEO.

BEKO2210/Firstbrain

AI-powered animation tool for creating motion in logos, UI, icons, and social media assets.

BEKO2210/Firstbrain

Best practices for Remotion - Video creation in React

BEKO2210/Firstbrain

Generate walkthrough videos from Stitch projects using Remotion with smooth transitions, zooming, and text overlays

BEKO2210/Firstbrain

Seek and analyze video content using Memories.ai Large Visual Memory Model for persistent video intelligence

BEKO2210/Firstbrain

Writes complete, structured landing pages optimized for SEO ranking, AEO citation, and visitor conversion. Activate when the user wants to write or generate a landing page for a product, service, or offer.

BEKO2210/Firstbrain

Automate TikTok tasks via Rube MCP (Composio): upload/publish videos, post photos, manage content, and view user profiles/stats. Always search tools first for current schemas.

BEKO2210/Firstbrain

Video and audio perception, indexing, and editing. Ingest files/URLs/live streams, build visual/spoken indexes, search with timestamps, edit timelines, add overlays/subtitles, generate media, and create real-time alerts.

BEKO2210/Firstbrain

Upload, stream, search, edit, transcribe, and generate AI video and audio using the VideoDB SDK.

BEKO2210/Firstbrain

One sentence - what this skill does and when to invoke it

BEKO2210/Firstbrain

Automate YouTube tasks via Rube MCP (Composio): upload videos, manage playlists, search content, get analytics, and handle comments. Always search tools first for current schemas.

BEKO2210/Firstbrain

Extract transcripts from YouTube videos and generate comprehensive, detailed summaries using intelligent analysis frameworks

関連スキル