# animation/animator (vanilla.js 0.4.0)

> https://vanillapunch.com/docs/vanilla.js/0.4.0/api/animation/animator/

애니메이터. (상태 기계로 스프라이트 클립을 고르고 섞는다)

## AnimationState extends Object

애니메이션 상태. (클립 하나를 속도와 되풀이 여부로 튼다)
- 상태 시간은 들어온 뒤 흐른 초에 속도를 곱해 쌓은 것이다. 정규화 시간은 상태 시간을 클립 길이로 나눈 것이다. (1 이면 한 바퀴)
- 되풀이는 setLoop 로 정하지 않으면(null) 클립의 isLoop 를 따른다.
- 클립이 없거나 길이가 0 이면 정규화 시간은 시간이 흐르기 전 0, 흐른 뒤 1 이다.

예제: 상태에 클립 달고 시간에 맞는 프레임 보기

```js
import { AnimationState, AnimationClip, Rect } from "./build/vanilla.js";

const clip = new AnimationClip();
clip.setFrames([Rect.create(0, 0, 32, 32), Rect.create(32, 0, 32, 32)]);
clip.setDuration(0.5);
clip.setLoop(false);
const state = new AnimationState();
state.setClip(clip);
state.setSpeed(2);
state.setLoop(true);
console.log(state.isLoop(), state.getNormalizedTime(0.75), state.getFrameIndex(0.75));
```

- `constructor()` (constructor, since 0.0.8): 생성.
- `setClip(clip)` (method, since 0.4.0): 클립 설정.
  - `clip` AnimationClip | null: 이 상태에서 쓸 클립. (null 이면 비운다)
- `getClip()` (method, since 0.4.0): 클립 반환. (없으면 null)
  - returns AnimationClip | null: 이 상태의 클립.
- `setSpeed(speed)` (method, since 0.4.0): 재생 속도 설정.
  - `speed` number: 재생 속도. (기본 1, 2 면 두 배로 빠르고 0 이면 멈춘다)
- `getSpeed()` (method, since 0.4.0): 재생 속도 반환.
  - returns number: 재생 속도. (기본 1)
- `setLoop(isLoop)` (method, since 0.4.0): 되풀이 여부 설정.
  - `isLoop` boolean | null: 되풀이하면 참. (null 이면 클립의 isLoop 를 따른다, 기본 null)
- `isLoop()` (method, since 0.4.0): 되풀이 여부 반환.
  - returns boolean: 되풀이하면 참. (setLoop 로 정하지 않았으면 클립의 isLoop, 클립도 없으면 거짓)
- `getDuration()` (method, since 0.4.0): 한 바퀴 길이 반환.
  - returns number: 클립의 지속 시간. (초, 클립이 없으면 0)
- `getNormalizedTime(time)` (method, since 0.4.0): 정규화 시간 반환.
  - `time` number: 상태 시간. (초, 속도를 곱해 쌓은 것)
  - returns number: 상태 시간을 한 바퀴 길이로 나눈 것. (1 이면 한 바퀴, 되풀이하면 1 을 넘어 쌓인다. 길이가 0 이면 시간이 흐르기 전 0, 흐른 뒤 1)
- `getFrameIndex(time)` (method, since 0.4.0): 프레임 번호 반환.
  - `time` number: 상태 시간. (초, 속도를 곱해 쌓은 것)
  - returns number | null: 그 시간에 보일 클립 프레임의 번호. (0 부터, 되풀이하면 바퀴마다 처음부터, 아니면 끝 프레임에 머문다. 길이가 0 이면 0, 클립이나 프레임이 없으면 null)

## AnimationTransition extends Object

애니메이션 전이. (조건이 맞으면 대상 상태로 넘어가는 상태 사이의 연결)
- from 이 null 이면 어느 상태에서나(Any State) 넘어간다. to 가 null 이거나 상태 목록 밖이면 쓰지 않는다.
- 종료 시각(exitTime)은 나가는 상태의 정규화 시간이다. 정해 두면 그 시각을 지나는 갱신에서만 넘어갈 수 있다.
  되풀이하는 상태에서 1 보다 작은 종료 시각은 바퀴마다 본다. (0.5 면 1.5, 2.5 에서도) 그 밖은 한 번만 본다.
- 조건은 모두 맞아야 한다. 종료 시각도 조건도 없는 전이는 쓰지 않는다.
- 섞는 시간(duration, 초)이 0 보다 크면 그동안 두 상태가 함께 흐르며 가중치가 선형으로 옮겨 간다. (크로스페이드)
- 어느 상태에서나 넘어가는 전이가 지금 상태로 가는 경우는 canTransitionToSelf 가 참일 때만 탄다. (기본 참, 다시 처음부터 튼다)

예제: 걷기에서 달리기로 가는 전이

```js
import { Animator, AnimationState, AnimationTransition, AnimationConditionMode } from "./build/vanilla.js";

const animator = new Animator();
const walkIndex = animator.addState(new AnimationState());
const runIndex = animator.addState(new AnimationState());
const transition = new AnimationTransition();
transition.setFrom(walkIndex);
transition.setTo(runIndex);
transition.setDuration(0.2);
transition.addCondition("speed", AnimationConditionMode.greater, 3);
animator.addTransition(transition);
const conditions = transition.getConditions();
console.log(transition.getFrom(), transition.getTo(), transition.getExitTime(), conditions[0].mode);
```

- `constructor()` (constructor, since 0.0.8): 생성.
- `setFrom(from)` (method, since 0.4.0): 나가는 상태 설정. (Animator.addState 가 돌려준 번호)
  - `from` number | null: 나가는 상태의 번호. (null 이면 어느 상태에서나, 기본 null)
- `getFrom()` (method, since 0.4.0): 나가는 상태 반환.
  - returns number | null: 나가는 상태의 번호. 어느 상태에서나 넘어가면 null.
- `setTo(to)` (method, since 0.4.0): 들어가는 상태 설정. (Animator.addState 가 돌려준 번호)
  - `to` number | null: 들어가는 상태의 번호. (null 이면 비우고, 빈 전이는 쓰지 않는다)
- `getTo()` (method, since 0.4.0): 들어가는 상태 반환.
  - returns number | null: 들어가는 상태의 번호. 정하지 않았으면 null.
- `setExitTime(exitTime)` (method, since 0.4.0): 종료 시각 설정.
  - `exitTime` number | null: 나가는 상태의 정규화 시간. (1 이면 한 바퀴 끝, null 이면 종료 시각 없이 조건만 본다, 기본 null)
- `getExitTime()` (method, since 0.4.0): 종료 시각 반환.
  - returns number | null: 종료 시각. (정규화 시간, 없으면 null)
- `setDuration(duration)` (method, since 0.4.0): 섞는 시간 설정.
  - `duration` number: 두 상태를 섞는 시간. (초, 0 이하이면 바로 넘어간다, 기본 0)
- `getDuration()` (method, since 0.4.0): 섞는 시간 반환.
  - returns number: 섞는 시간. (초)
- `setCanTransitionToSelf(canTransitionToSelf)` (method, since 0.4.0): 지금 상태로 가는 것을 허락할지 설정.
  - `canTransitionToSelf` boolean: 참이면 어느 상태에서나 넘어가는 전이가 지금 상태로도 간다. (기본 참, from 이 정해진 전이에는 쓰지 않는다)
- `canTransitionToSelf()` (method, since 0.4.0): 지금 상태로 가는 것을 허락하는지 반환.
  - returns boolean: 어느 상태에서나 넘어가는 전이가 지금 상태로도 가면 참.
- `addCondition(parameterName, mode, threshold = 0)` (method, since 0.4.0): 조건 추가.
  - `parameterName` string: 견줄 매개변수 이름.
  - `mode` string: 견주는 법. (AnimationConditionMode 의 값)
  - `threshold` number: 기준 값. (greater, less, equals, notEqual 에서 쓴다, 기본 0)
- `getConditions()` (method, since 0.4.0): 조건 목록 반환.
  - returns { parameterName: string, mode: string, threshold: number }[]: 넣은 차례의 조건 목록. (복사본이 아니다)
- `isExitTimeReached(state, previousTime, currentTime)` (method, since 0.4.0): 종료 시각을 지났는지 반환.
  - `state` AnimationState: 나가는 상태.
  - `previousTime` number: 이번 갱신 앞의 상태 시간. (초)
  - `currentTime` number: 이번 갱신 뒤의 상태 시간. (초)
  - returns boolean: 종료 시각이 없거나, 이번 갱신에서 종료 시각을 지났으면 참. (길이가 0 인 상태는 들어온 뒤 첫 갱신에서 지난다)

## Animator extends Object

애니메이터. (상태 기계로 스프라이트 클립을 고르고 섞는다)
- 처음 더한 상태에서 시작한다. play 로 아무 상태로나 바로 옮길 수 있다.
- 매개변수는 실수(setFloat), 정수(setInteger), 참 거짓(setBool), 트리거(setTrigger) 넷이다. 같은 이름을 다른 종류로 넣으면 종류째 바꾼다.
  트리거는 그 트리거를 조건으로 쓴 전이가 타면 풀린다. (resetTrigger 로 직접 풀 수도 있다)
- tick 차례: 상태 시간을 흘린다(섞는 중이면 두 상태 모두) → 섞는 중이면 섞는 시간을 다 채웠을 때 다음 상태로 넘어간다
  → 섞는 중이 아니면 어느 상태에서나 넘어가는 전이, 지금 상태에서 나가는 전이 차례로 넣은 순서대로 보고 처음 맞는 하나를 탄다.
  섞는 동안에는 새 전이를 보지 않는다.
- 섞는 중의 가중치: 다음 상태가 getTransitionWeight(섞은 시간 / 섞는 시간), 지금 상태가 1 - 그 값이다.
- 고른 프레임은 getCurrentFrame, getNextFrame 으로 꺼낸다. (클립 프레임 목록의 것, Frame 이나 Rect)

예제: 속도로 걷기와 달리기를 오가는 애니메이터

```js
import { Animator, AnimationState, AnimationTransition, AnimationClip, AnimationConditionMode, Rect } from "./build/vanilla.js";

const walkClip = new AnimationClip();
walkClip.setFrames([Rect.create(0, 0, 32, 32), Rect.create(32, 0, 32, 32)]);
walkClip.setDuration(1);
walkClip.setLoop(true);
const runClip = new AnimationClip();
runClip.setFrames([Rect.create(0, 32, 32, 32), Rect.create(32, 32, 32, 32)]);
runClip.setDuration(0.5);
runClip.setLoop(true);

const animator = new Animator();
const walkState = new AnimationState();
walkState.setClip(walkClip);
const runState = new AnimationState();
runState.setClip(runClip);
const walkIndex = animator.addState(walkState);
const runIndex = animator.addState(runState);
const toRun = new AnimationTransition();
toRun.setFrom(walkIndex);
toRun.setTo(runIndex);
toRun.setDuration(0.25);
toRun.addCondition("speed", AnimationConditionMode.greater, 3);
animator.addTransition(toRun);
const toWalk = new AnimationTransition();
toWalk.setFrom(runIndex);
toWalk.setTo(walkIndex);
toWalk.addCondition("speed", AnimationConditionMode.less, 1);
animator.addTransition(toWalk);

animator.setFloat("speed", 5);
animator.tick(0.125);
console.log(animator.getCurrentStateIndex(), animator.getNextStateIndex(), animator.getTransitionWeight());
animator.tick(0.125);
console.log(animator.getNextStateIndex(), animator.getTransitionWeight());
animator.tick(0.125);
const frame = animator.getCurrentFrame();
console.log(animator.getCurrentStateIndex(), animator.isInTransition(), frame.position.y);
```

예제: 트리거로 어느 상태에서나(Any State) 넘어가는 피격과 종료 시각으로 돌아오기

```js
import { Animator, AnimationState, AnimationTransition, AnimationClip, AnimationConditionMode, Rect } from "./build/vanilla.js";

const createState = (duration, isLoop) => {
	const clip = new AnimationClip();
	clip.setFrames([Rect.create(0, 0, 32, 32), Rect.create(32, 0, 32, 32)]);
	clip.setDuration(duration);
	clip.setLoop(isLoop);
	const state = new AnimationState();
	state.setClip(clip);
	return state;
};

const animator = new Animator();
const idleIndex = animator.addState(createState(1, true));
const runIndex = animator.addState(createState(0.5, true));
const hitIndex = animator.addState(createState(0.5, false));
const toRun = new AnimationTransition();
toRun.setFrom(idleIndex);
toRun.setTo(runIndex);
toRun.addCondition("isRunning", AnimationConditionMode.if);
animator.addTransition(toRun);
const anyToHit = new AnimationTransition();
anyToHit.setTo(hitIndex);
anyToHit.setCanTransitionToSelf(false);
anyToHit.addCondition("hit", AnimationConditionMode.if);
animator.addTransition(anyToHit);
const hitToIdle = new AnimationTransition();
hitToIdle.setFrom(hitIndex);
hitToIdle.setTo(idleIndex);
hitToIdle.setExitTime(1);
animator.addTransition(hitToIdle);

animator.setBool("isRunning", true);
animator.tick(0.1);
console.log(animator.getCurrentStateIndex() === runIndex);
animator.setTrigger("hit");
animator.tick(0.1);
console.log(animator.getCurrentStateIndex() === hitIndex, animator.getTrigger("hit"));

animator.setTrigger("hit");
animator.tick(0.1);
console.log(animator.getCurrentStateIndex() === hitIndex, animator.getTrigger("hit"));
animator.resetTrigger("hit");
animator.setBool("isRunning", false);
animator.tick(0.5);
console.log(animator.getCurrentStateIndex() === idleIndex);
```

- `constructor()` (constructor, since 0.0.8): 생성.
- `tick(timeDelta)` (method, since 0.0.8): 갱신.
  - `timeDelta` number: 지난 프레임부터의 시간. (초, 상태마다 속도를 곱해 흘린다)
- `play(stateIndex)` (method, since 0.4.0): 상태 바로 틀기. (섞지 않고 처음부터)
  - `stateIndex` number: 틀 상태의 번호. (Animator.addState 가 돌려준 것, 목록 밖이면 무시한다)
- `findTransition(previousTime)` (method, since 0.4.0): 탈 전이 찾기.
  - `previousTime` number: 이번 갱신 앞의 지금 상태 시간. (초, 종료 시각을 지났는지 볼 때 쓴다)
  - returns number | null: 처음 맞는 전이의 번호. (어느 상태에서나 넘어가는 전이를 먼저, 그다음 지금 상태에서 나가는 전이를 넣은 순서대로 본다, 섞는 중이거나 없으면 null)
- `startTransition(transitionIndex)` (method, since 0.4.0): 전이 타기. (조건과 종료 시각은 보지 않는다)
  - `transitionIndex` number: 탈 전이의 번호. (Animator.addTransition 이 돌려준 것, 목록 밖이거나 들어가는 상태가 목록 밖이면 무시한다)
- `isConditionSatisfied(condition)` (method, since 0.4.0): 조건이 맞는지 반환.
  - `condition` { parameterName: string, mode: string, threshold: number }: 볼 조건. (AnimationTransition.getConditions 의 요소)
  - returns boolean: 지금 매개변수로 조건이 맞으면 참. (매개변수가 없거나 견줄 수 없는 종류면 거짓)
- `setFloat(name, value)` (method, since 0.4.0): 실수 매개변수 설정.
  - `name` string: 매개변수 이름.
  - `value` number: 값. (같은 이름이 있으면 종류째 바꾼다)
- `getFloat(name)` (method, since 0.4.0): 실수 매개변수 반환.
  - `name` string: 매개변수 이름.
  - returns number: 값. (없거나 실수가 아니면 0)
- `setInteger(name, value)` (method, since 0.4.0): 정수 매개변수 설정.
  - `name` string: 매개변수 이름.
  - `value` number: 값. (소수점 아래는 버린다, 같은 이름이 있으면 종류째 바꾼다)
- `getInteger(name)` (method, since 0.4.0): 정수 매개변수 반환.
  - `name` string: 매개변수 이름.
  - returns number: 값. (없거나 정수가 아니면 0)
- `setBool(name, value)` (method, since 0.4.0): 참 거짓 매개변수 설정.
  - `name` string: 매개변수 이름.
  - `value` boolean: 값. (같은 이름이 있으면 종류째 바꾼다)
- `getBool(name)` (method, since 0.4.0): 참 거짓 매개변수 반환.
  - `name` string: 매개변수 이름.
  - returns boolean: 값. (없거나 참 거짓이 아니면 거짓)
- `setTrigger(name)` (method, since 0.4.0): 트리거 걸기. (그 트리거를 조건으로 쓴 전이가 타면 풀린다)
  - `name` string: 매개변수 이름. (같은 이름이 있으면 종류째 바꾼다)
- `resetTrigger(name)` (method, since 0.4.0): 트리거 풀기.
  - `name` string: 매개변수 이름. (같은 이름이 있으면 종류째 바꾼다)
- `getTrigger(name)` (method, since 0.4.0): 트리거가 걸려 있는지 반환.
  - `name` string: 매개변수 이름.
  - returns boolean: 걸려 있으면 참. (없거나 트리거가 아니면 거짓)
- `getParameters()` (method, since 0.4.0): 모든 매개변수 반환.
  - returns Dictionary<string, { type: string, value: number | boolean }>: 매개변수 이름과 종류, 값의 딕셔너리. (type 은 float, int, bool, trigger, 복사본이 아니다)
- `addState(state)` (method, since 0.4.0): 상태 추가. (상태 목록의 번호를 돌려준다, 처음 더한 상태에서 시작한다)
  - `state` AnimationState: 더할 상태.
  - returns number: 더한 상태의 번호. (0 부터)
- `getStates()` (method, since 0.4.0): 상태 목록 반환.
  - returns List<AnimationState>: 상태 목록. (복사본이 아니다)
- `addTransition(transition)` (method, since 0.4.0): 전이 추가. (전이 목록의 번호를 돌려준다)
  - `transition` AnimationTransition: 더할 전이.
  - returns number: 더한 전이의 번호. (0 부터)
- `getTransitions()` (method, since 0.4.0): 전이 목록 반환.
  - returns List<AnimationTransition>: 전이 목록. (복사본이 아니다)
- `getCurrentStateIndex()` (method, since 0.4.0): 지금 상태 반환.
  - returns number | null: 지금 상태의 번호. (섞는 중이면 나가는 상태, 상태가 없으면 null)
- `getCurrentNormalizedTime()` (method, since 0.4.0): 지금 상태의 정규화 시간 반환.
  - returns number: 지금 상태 시간을 한 바퀴 길이로 나눈 것. (상태가 없으면 0)
- `getCurrentFrame()` (method, since 0.4.0): 지금 상태의 프레임 반환.
  - returns Frame | Rect | null: 지금 상태 시간에 보일 클립 프레임. (클립 프레임 목록의 것, 상태나 클립이나 프레임이 없으면 null)
- `isInTransition()` (method, since 0.4.0): 섞는 중인지 반환.
  - returns boolean: 두 상태를 섞는 중이면 참.
- `getNextStateIndex()` (method, since 0.4.0): 섞으며 들어가는 상태 반환.
  - returns number | null: 들어가는 상태의 번호. (섞는 중이 아니면 null)
- `getNextNormalizedTime()` (method, since 0.4.0): 들어가는 상태의 정규화 시간 반환.
  - returns number: 들어가는 상태 시간을 한 바퀴 길이로 나눈 것. (섞는 중이 아니면 0)
- `getNextFrame()` (method, since 0.4.0): 들어가는 상태의 프레임 반환.
  - returns Frame | Rect | null: 들어가는 상태 시간에 보일 클립 프레임. (섞는 중이 아니거나 클립이나 프레임이 없으면 null)
- `getTransitionWeight()` (method, since 0.4.0): 들어가는 상태의 가중치 반환. (크로스페이드)
  - returns number: 섞은 시간 / 섞는 시간. (0 ~ 1, 지금 상태의 가중치는 1 - 이 값, 섞는 중이 아니면 0)

## AnimationConditionMode (enum)

전이 조건의 견주는 법.
- if, ifNot 은 참 거짓 매개변수를 본다. (if 는 트리거가 걸려 있는 것도 본다)
- greater, less, equals, notEqual 은 실수와 정수 매개변수를 기준 값과 견준다.

- `if` = `if`: 참 거짓 매개변수가 참이거나 트리거가 걸려 있다.
- `ifNot` = `ifNot`: 참 거짓 매개변수가 거짓이다.
- `greater` = `greater`: 수 매개변수가 기준 값보다 크다.
- `less` = `less`: 수 매개변수가 기준 값보다 작다.
- `equals` = `equals`: 수 매개변수가 기준 값과 같다.
- `notEqual` = `notEqual`: 수 매개변수가 기준 값과 다르다.
