Communitygithub.com

ASoudy/AGS

Three.js 动画 - 关键帧动画、骨骼动画、形态目标、动画混合。用于对象动画、播放 GLTF 动画、创建程序化运动或混合动画。

AGS 是什么?

此技能为开发者提供完整的 Three.js 动画系统指南,涵盖从基础的关键帧动画到高级的骨骼动画和形态目标。它详细说明了 AnimationClip、AnimationMixer 和 AnimationAction 三大组件的用法,并提供了程序化动画模式,如平滑阻尼、弹簧物理和振荡。技能适用于 Three.js 中的一切动画任务,包括加载和播放 GLTF 动画以及多动画混合。此外,它还包括性能优化建议和实用的代码示例,确保开发者能高效地创建复杂的运动行为。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/ASoudy/AGS/tree/HEAD/AGAS/plugins/antigravity-awesome-skills-claude/skills/threejs-animation

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

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 动画系统包含三个主要组件:

  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);

// 插值
track.setInterpolation(THREE.InterpolateLinear); // 默认
track.setInterpolation(THREE.InterpolateSmooth); // 三次样条
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; // 播放一次后停止
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();

程序化动画模式

平滑阻尼

// 平滑跟随/线性插值
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 - 着色器中的顶点动画

限制

  • 仅当任务明显符合上述范围时使用此技能。
  • 不要将输出视为特定环境验证、测试或专家审查的替代品。
  • 如果缺少必要的输入、权限、安全边界或成功标准,请停止并寻求澄清。

Individual skills in this repo

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

ASoudy/AGS

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

ASoudy/AGS

Astropy is the core Python package for astronomy, providing essential functionality for astronomical research and data analysis.

ASoudy/AGS

Build content-focused websites with Astro — zero JS by default, islands architecture, multi-framework components, and Markdown/MDX support.

ASoudy/AGS

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

ASoudy/AGS

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.

ASoudy/AGS

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

ASoudy/AGS

Pull a YouTube video transcript into a queryable markdown vault with yt-dlp subtitle discovery, VTT cleanup, metadata frontmatter, and capture-seed stubs.

ASoudy/AGS

Expert in building portfolios that actually land jobs and clients - not just showing work, but creating memorable experiences. Covers developer portfolios, designer portfolios, creative portfolios, and portfolios that convert visitors into opportunities.

ASoudy/AGS

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.

ASoudy/AGS

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

ASoudy/AGS

CRITICAL: Use for Makepad animation system. Triggers on: makepad animation, makepad animator, makepad hover, makepad state, makepad transition, "from: { all: Forward", makepad pressed, makepad 动画, makepad 状态, makepad 过渡, makepad 悬停效果

ASoudy/AGS

Comprehensive patterns for Next.js 14+ App Router architecture, Server Components, and modern full-stack React development.

ASoudy/AGS

Next.js App Router principles. Server Components, data fetching, routing patterns.

ASoudy/AGS

Expert integration of Supabase Auth with Next.js App Router

ASoudy/AGS

React and Next.js 14+ application development with App Router, Server Components, TypeScript, Tailwind CSS, and modern frontend patterns.

ASoudy/AGS

Best practices for Remotion - Video creation in React

ASoudy/AGS

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

ASoudy/AGS

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

ASoudy/AGS

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.

ASoudy/AGS

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

相关技能