threejs-impl-animation
빠른 참고
아키텍처
AnimationClip (데이터: KeyframeTrack 객체 배열)
└── AnimationAction (재생 컨트롤러: play, pause, fade, crossfade)
└── AnimationMixer (마스터 스케줄러: 애니메이션 루트 객체당 하나)
└── Clock (mixer.update에 델타 시간 제공)
애니메이션 루트 객체당 정확히 하나의 AnimationMixer를 생성하세요.
렌더 루프 안에서 매 프레임 mixer.update(delta)를 호출하세요.
AnimationAction을 직접 인스턴스화하지 마세요 -- 항상 mixer.clipAction(clip)을 사용하세요.
필수 임포트
import * as THREE from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
최소 애니메이션 설정
import * as THREE from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
const clock = new THREE.Clock();
let mixer;
const loader = new GLTFLoader();
loader.load('character.glb', (gltf) => {
scene.add(gltf.scene);
mixer = new THREE.AnimationMixer(gltf.scene);
// GLTF 파일의 모든 애니메이션 재생
gltf.animations.forEach((clip) => {
mixer.clipAction(clip).play();
});
});
function animate() {
const delta = clock.getDelta();
if (mixer) mixer.update(delta);
renderer.render(scene, camera);
}
renderer.setAnimationLoop(animate);
중요 경고
절대 렌더 루프에서 mixer.update(delta)를 호출하는 것을 잊지 마세요 -- 호출하지 않으면 애니메이션이 재생되지 않습니다.
절대 수동으로 델타를 계산하기 위해 new Date() 또는 performance.now()를 사용하지 마세요 -- 항상 THREE.Clock 또는 안정적인 프레임 타이밍을 제공하는 renderer.setAnimationLoop를 사용하세요.
절대 렌더 루프에서 mixer.clipAction(clip)을 반복해서 호출하지 마세요 -- 내부적으로 캐싱되지만 불필요한 조회 오버헤드가 발생합니다. 항상 반환된 액션을 변수에 저장하세요.
절대 매 프레임 .play()를 호출하지 마세요 -- 재생을 시작하려면 한 번만 호출하세요. 이미 재생 중인 액션에 .play()를 다시 호출해도 효과는 없지만, 잘못된 이해를 나타냅니다.
정지되었거나 완료된 액션을 다시 시작할 때는 항상 .play() 전에 .reset()을 호출하세요. 그렇지 않으면 액션이 마지막 위치에서 다시 시작될 수 있습니다.
LoopOnce를 사용할 때는 항상 action.clampWhenFinished = true로 설정하세요 -- 그렇지 않으면 액션이 완료 시 첫 프레임으로 리셋됩니다.
AnimationMixer
단일 객체 계층 구조에 대한 모든 애니메이션 액션을 구동하는 마스터 스케줄러입니다.
생성자
const mixer = new THREE.AnimationMixer(rootObject);
rootObject는 애니메이션 모델의 루트 Object3D입니다 (일반적으로 gltf.scene).
속성
| 속성 | 타입 | 기본값 | 설명 |
|---|---|---|---|
.time | number | 0 | 전역 믹서 시간 (초) |
.timeScale | number | 1 | 전역 속도 배수; 0이면 모든 액션 일시 정지 |
메서드
| 메서드 | 반환값 | 설명 |
|---|---|---|
.clipAction(clip, root?, blendMode?) | AnimationAction | 클립에 대한 액션을 반환하거나 생성 |
.existingAction(clip, root?) | AnimationAction | null | 이전에 생성된 액션을 반환하거나 null |
.update(delta) | this | 믹서를 delta초만큼 전진 -- 매 프레임 호출 필수 |
.setTime(seconds) | this | 전역 시간 설정, 모든 액션 업데이트 |
.stopAllAction() | this | 모든 예약된 액션 비활성화 |
.getRoot() | Object3D | 믹서의 루트 객체 반환 |
.uncacheAction(clip, root?) | void | 캐시된 액션 해제 |
.uncacheClip(clip) | void | 클립 데이터 해제 |
.uncacheRoot(root) | void | 루트 객체 데이터 해제 |
이벤트
mixer.addEventListener(type, callback)을 통해 수신:
| 이벤트 | 발생 시점 |
|---|---|
'finished' | 액션 완료 (LoopOnce + clampWhenFinished = true에서만) |
'loop' | 액션이 루프 반복을 완료 |
이벤트 객체 속성: { action, loopDelta, type }.
블렌드 모드
mixer.clipAction(clip, root, blendMode)의 세 번째 인자로 전달:
| 상수 | 동작 |
|---|---|
THREE.NormalAnimationBlendMode | 표준 블렌딩 (기본값) |
THREE.AdditiveAnimationBlendMode | 기본 애니메이션 위에 레이어링 |
AnimationAction
단일 애니메이션 클립의 재생을 제어합니다. 직접 인스턴스화하지 마세요.
속성
| 속성 | 타입 | 기본값 | 설명 |
|---|---|---|---|
.blendMode | number | NormalAnimationBlendMode | 블렌딩 전략 |
.clampWhenFinished | boolean | false | 종료 시 마지막 프레임에서 일시 정지 |
.enabled | boolean | true | 리셋 없이 비활성화 |
.loop | number | LoopRepeat | 루프 모드 |
.paused | boolean | false | 재생 일시 정지 |
.repetitions | number | Infinity | 루프 횟수 |
.time | number | 0 | 로컬 시간 (초) |
.timeScale | number | 1 | 속도: 0은 일시 정지, 음수는 역방향 |
.weight | number | 1 | 블렌드 영향 [0, 1] |
.zeroSlopeAtEnd | boolean | true | 루프 끝에서 부드러운 보간 |
.zeroSlopeAtStart | boolean | true | 루프 시작에서 부드러운 보간 |
루프 모드
| 상수 | 동작 |
|---|---|
THREE.LoopOnce | 한 번 재생 후 정지 |
THREE.LoopRepeat | 각 루프마다 처음부터 다시 시작 |
THREE.LoopPingPong | 앞/뒤로 번갈아 재생 |
재생 메서드
| 메서드 | 설명 |
|---|---|
.play() | 재생 시작 |
.stop() | 정지 후 시작점으로 리셋 |
.reset() | 시간, 가중치, 속도를 초기 상태로 리셋 |
.startAt(mixerTime) | 지정된 믹서 시간까지 시작 지연 |
페이딩 및 크로스페이드 메서드
| 메서드 | 설명 |
|---|---|
.fadeIn(duration) | 가중치를 0에서 1로 페이드 |
.fadeOut(duration) | 가중치를 1에서 0으로 페이드 |
.crossFadeFrom(fadeOutAction, duration, warp) | 다른 액션에서 현재 액션으로 크로스페이드 |
.crossFadeTo(fadeInAction, duration, warp) | 현재 액션에서 다른 액션으로 크로스페이드 |
.stopFading() | 활성화된 페이드 취소 |
속도 및 타이밍 메서드
| 메서드 | 설명 |
|---|---|
.halt(duration) | duration 동안 timeScale을 0으로 감속 |
.warp(startScale, endScale, duration) | 재생 속도를 부드럽게 전환 |
.stopWarping() | 활성화된 warp 취소 |
.setDuration(seconds) | 한 루프가 정확히 seconds초가 걸리도록 timeScale 조정 |
.setEffectiveTimeScale(scale) | 유효 시간 스케일 설정 |
.setEffectiveWeight(weight) | 유효 가중치 설정 |
.setLoop(mode, repetitions) | 루프 모드 및 횟수 설정 |
.syncWith(otherAction) | 다른 액션과 시간 동기화 |
질의 메서드
| 메서드 | 반환값 | 설명 |
|---|---|---|
.isRunning() | boolean | 활발히 재생 중일 때만 true |
.isScheduled() | boolean | .play()가 호출되었으면 true |
.getClip() | AnimationClip | 연결된 클립 |
.getMixer() | AnimationMixer | 소유 믹서 |
.getRoot() | Object3D | 루트 객체 |
.getEffectiveTimeScale() | number | 계산된 시간 스케일 |
.getEffectiveWeight() | number | 계산된 가중치 |
AnimationClip
재사용 가능한 키프레임 트랙 세트입니다. 일반적으로 GLTF 파일에서 로드됩니다.
생성자
const clip = new THREE.AnimationClip(name, duration, tracks, blendMode);
name-- 문자열 식별자 (GLTF 클립은 파일의 이름 사용)duration-- 초;-1은 트랙에서 자동 계산tracks--KeyframeTrack객체 배열blendMode-- 선택적 블렌드 모드 상수
주요 정적 메서드
| 메서드 | 설명 |
|---|---|
AnimationClip.findByName(arrayOrObject, name) | 이름으로 클립 검색 |
AnimationClip.CreateFromMorphTargetSequence(name, targets, fps, noLoop) | 모프 타겟에서 클립 생성 |
AnimationClip.parse(json) | JSON에서 역직렬화 |
KeyframeTrack 타입
| 트랙 타입 | 값 타입 | 사용 사례 |
|---|---|---|
VectorKeyframeTrack | Vector3 | 위치, 스케일 |
QuaternionKeyframeTrack | Quaternion | 회전 (slerp 사용) |
NumberKeyframeTrack | number | 불투명도, 강도 |
BooleanKeyframeTrack | boolean | 가시성 토글 |
ColorKeyframeTrack | Color | 색상 애니메이션 |
StringKeyframeTrack | string | 이산 문자열 값 |
보간 모드
| 상수 | 동작 |
|---|---|
THREE.InterpolateDiscrete | 계단 함수, 스무딩 없음 |
THREE.InterpolateLinear | 선형 보간 (기본값) |
THREE.InterpolateSmooth | 3차 스플라인 보간 |
PropertyBinding 경로 형식
"meshName.position" // 위치 애니메이션
"meshName.material.opacity" // 머티리얼 속성 애니메이션
"meshName.morphTargetInfluences[0]" // 모프 타겟 애니메이션
"boneName.quaternion" // 본 회전 애니메이션
Clock
생성자
const clock = new THREE.Clock(autoStart); // autoStart 기본값은 true
메서드
| 메서드 | 반환값 | 설명 |
|---|---|---|
.getDelta() | number | 마지막 getDelta() 호출 이후 경과 시간 (초) |
.getElapsedTime() | number | 총 경과 시간 (초) |
.start() | void | 시계 시작 |
.stop() | void | 리셋 없이 정지 |
크로스페이드 패턴 (캐릭터 상태 머신)
const actions = {};
gltf.animations.forEach((clip) => {
actions[clip.name] = mixer.clipAction(clip);
});
let currentAction = actions['Idle'];
currentAction.play();
function switchAction(toName, duration = 0.5) {
const toAction = actions[toName];
toAction.reset();
toAction.setEffectiveTimeScale(1);
toAction.setEffectiveWeight(1);
toAction.crossFadeFrom(currentAction, duration, true);
toAction.play();
currentAction = toAction;
}
크로스페이드하기 전에 들어오는 액션에 대해 항상 .reset()을 호출하세요.
다음 전환을 위해 항상 현재 액션 참조를 저장하세요.
가산 애니메이션 블렌딩
const baseAction = mixer.clipAction(baseClip);
const additiveAction = mixer.clipAction(
additiveClip, undefined, THREE.AdditiveAnimationBlendMode
);
baseAction.play();
additiveAction.play();
additiveAction.setEffectiveWeight(0.5);
가산 블렌딩은 레이어 효과에 사용하세요: 호흡, 피해 반응, 조준 오프셋.
모프 타겟 애니메이션
// 수동 제어
mesh.morphTargetInfluences[0] = Math.sin(elapsed) * 0.5 + 0.5;
// GLTF 애니메이션 클립을 통해 (권장)
const morphAction = mixer.clipAction(morphClip);
morphAction.play();
참고 링크
- references/methods.md -- 전체 API 시그니처
- references/examples.md -- 실제 동작하는 코드 예제
- references/anti-patterns.md -- 하지 말아야 할 것들
공식 출처
- https://threejs.org/docs/#api/en/animation/AnimationMixer
- https://threejs.org/docs/#api/en/animation/AnimationAction
- https://threejs.org/docs/#api/en/animation/AnimationClip
- https://threejs.org/docs/#api/en/animation/KeyframeTrack
- https://threejs.org/docs/#api/en/core/Clock
- https://threejs.org/examples/#webgl_animation_skinning_blending