# animation/animator (vanilla.js 0.4.0)

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

Animator. (Picks and blends sprite clips with a state machine)

## AnimationState extends Object

Animation state. (Plays one clip with a speed and a loop flag)
- The state time is the seconds since entering, multiplied by the speed and accumulated. The normalized time is the state time divided by the clip length. (1 is one cycle)
- If the loop is not set with setLoop (null), it follows the clip's isLoop.
- With no clip or a zero length, the normalized time is 0 before any time passes and 1 after.

Example: Attach a clip to a state and look up the frame for a time

```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): Constructor.
- `setClip(clip)` (method, since 0.4.0): Sets the clip.
  - `clip` AnimationClip | null: Clip used in this state. (cleared if null)
- `getClip()` (method, since 0.4.0): Returns the clip. (null if none)
  - returns AnimationClip | null: Clip of this state.
- `setSpeed(speed)` (method, since 0.4.0): Sets the playback speed.
  - `speed` number: Playback speed. (Default 1, 2 plays twice as fast and 0 stops)
- `getSpeed()` (method, since 0.4.0): Get the playback speed.
  - returns number: Playback speed. (Default 1)
- `setLoop(isLoop)` (method, since 0.4.0): Set whether it loops.
  - `isLoop` boolean | null: True to loop. (null follows the clip's isLoop, default null)
- `isLoop()` (method, since 0.4.0): Get whether it loops.
  - returns boolean: True if it loops. (The clip's isLoop when not set with setLoop, false when there is no clip either)
- `getDuration()` (method, since 0.4.0): Get the length of one cycle.
  - returns number: Duration of the clip. (Seconds, 0 when there is no clip)
- `getNormalizedTime(time)` (method, since 0.4.0): Get the normalized time.
  - `time` number: State time. (Seconds, accumulated with the speed applied)
  - returns number: State time divided by the length of one cycle. (1 is one cycle, a looping state keeps accumulating past 1. With a zero length, 0 before any time passes and 1 after)
- `getFrameIndex(time)` (method, since 0.4.0): Get the frame index.
  - `time` number: State time. (Seconds, accumulated with the speed applied)
  - returns number | null: Index of the clip frame shown at that time. (From 0, a looping state restarts every cycle, otherwise it stays on the last frame. 0 for a zero length, null when there is no clip or no frames)

## AnimationTransition extends Object

Animation transition. (A link between states that moves to the target state when its conditions hold)
- With a null from, it moves from any state (Any State). A transition whose to is null or outside the state list is not used.
- The exit time is the normalized time of the leaving state. When set, the transition can only happen on the update that passes that time.
  For a looping state, an exit time below 1 is checked every cycle (0.5 also at 1.5, 2.5). Otherwise it is checked only once.
- All conditions must hold. A transition with neither an exit time nor conditions is not used.
- If the blend time (duration, seconds) is above 0, both states run together for that time while the weight moves linearly. (Crossfade)
- A transition from any state that leads to the current state is taken only when canTransitionToSelf is true. (Default true, the state restarts from the beginning)

Example: Transition from walking to running

```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): Constructor.
- `setFrom(from)` (method, since 0.4.0): Sets the outgoing state. (The number returned by Animator.addState)
  - `from` number | null: Index of the leaving state. (null means any state, default null)
- `getFrom()` (method, since 0.4.0): Returns the outgoing state.
  - returns number | null: Index of the leaving state. null when it moves from any state.
- `setTo(to)` (method, since 0.4.0): Sets the incoming state. (The number returned by Animator.addState)
  - `to` number | null: Index of the entering state. (null clears it, an empty transition is not used)
- `getTo()` (method, since 0.4.0): Returns the incoming state.
  - returns number | null: Index of the state to enter. null if not set.
- `setExitTime(exitTime)` (method, since 0.4.0): Set the exit time.
  - `exitTime` number | null: Normalized time of the leaving state. (1 is the end of one cycle, null checks only the conditions without an exit time, default null)
- `getExitTime()` (method, since 0.4.0): Get the exit time.
  - returns number | null: Exit time. (Normalized time, null when there is none)
- `setDuration(duration)` (method, since 0.4.0): Set the blend time.
  - `duration` number: Time to blend the two states. (Seconds, 0 or less moves immediately, default 0)
- `getDuration()` (method, since 0.4.0): Get the blend time.
  - returns number: Blend time. (Seconds)
- `setCanTransitionToSelf(canTransitionToSelf)` (method, since 0.4.0): Set whether moving to the current state is allowed.
  - `canTransitionToSelf` boolean: True lets a transition from any state also lead to the current state. (Default true, not used by transitions with a set from)
- `canTransitionToSelf()` (method, since 0.4.0): Get whether moving to the current state is allowed.
  - returns boolean: True if a transition from any state also leads to the current state.
- `addCondition(parameterName, mode, threshold = 0)` (method, since 0.4.0): Add a condition.
  - `parameterName` string: Name of the parameter to compare.
  - `mode` string: How to compare. (A value of AnimationConditionMode)
  - `threshold` number: Threshold. (Used by greater, less, equals, notEqual, default 0)
- `getConditions()` (method, since 0.4.0): Get the condition list.
  - returns { parameterName: string, mode: string, threshold: number }[]: Conditions in the order they were added. (Not a copy)
- `isExitTimeReached(state, previousTime, currentTime)` (method, since 0.4.0): Get whether the exit time was passed.
  - `state` AnimationState: Leaving state.
  - `previousTime` number: State time before this update. (Seconds)
  - `currentTime` number: State time after this update. (Seconds)
  - returns boolean: True if there is no exit time, or this update passed the exit time. (A zero-length state passes it on the first update after entering)

## Animator extends Object

Animator. (Picks and blends sprite clips with a state machine)
- It starts in the first added state. play moves to any state immediately.
- There are four parameter kinds: float (setFloat), integer (setInteger), boolean (setBool), and trigger (setTrigger). Setting the same name with another kind replaces the kind.
  A trigger is cleared when a transition that uses it as a condition is taken. (resetTrigger also clears it)
- tick order: advance the state time (both states while blending) → while blending, move to the next state once the blend time is filled
  → when not blending, check transitions from any state, then transitions leaving the current state, each in the order added, and take the first one that holds.
  No new transition is checked while blending.
- Weights while blending: the next state gets getTransitionWeight (blended time / blend time) and the current state gets 1 minus that.
- The chosen frames come from getCurrentFrame and getNextFrame. (Entries of the clip frame list, Frame or Rect)

Example: Animator that switches between walking and running by speed

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

Example: A trigger-driven hit from any state (Any State), returning by exit time

```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): Constructor.
- `tick(timeDelta)` (method, since 0.0.8): Update.
  - `timeDelta` number: Time since the last frame. (Seconds, each state applies its speed)
- `play(stateIndex)` (method, since 0.4.0): Play a state immediately. (From the beginning, without blending)
  - `stateIndex` number: Index of the state to play. (Returned by Animator.addState, ignored when outside the list)
- `findTransition(previousTime)` (method, since 0.4.0): Find the transition to take.
  - `previousTime` number: Current state time before this update. (Seconds, used to check whether the exit time was passed)
  - returns number | null: Index of the first transition that holds. (Transitions from any state are checked first, then transitions leaving the current state, each in the order added. null while blending or when none holds)
- `startTransition(transitionIndex)` (method, since 0.4.0): Take a transition. (Conditions and exit time are not checked)
  - `transitionIndex` number: Index of the transition to take. (Returned by Animator.addTransition, ignored when outside the list or when the entering state is outside the list)
- `isConditionSatisfied(condition)` (method, since 0.4.0): Get whether a condition holds.
  - `condition` { parameterName: string, mode: string, threshold: number }: Condition to check. (An entry of AnimationTransition.getConditions)
  - returns boolean: True if the condition holds with the current parameters. (False when the parameter is missing or its kind cannot be compared)
- `setFloat(name, value)` (method, since 0.4.0): Set a float parameter.
  - `name` string: Parameter name.
  - `value` number: Value. (Replaces the kind when the same name exists)
- `getFloat(name)` (method, since 0.4.0): Get a float parameter.
  - `name` string: Parameter name.
  - returns number: Value. (0 when missing or not a float)
- `setInteger(name, value)` (method, since 0.4.0): Set an integer parameter.
  - `name` string: Parameter name.
  - `value` number: Value. (The fraction is dropped, replaces the kind when the same name exists)
- `getInteger(name)` (method, since 0.4.0): Get an integer parameter.
  - `name` string: Parameter name.
  - returns number: Value. (0 when missing or not an integer)
- `setBool(name, value)` (method, since 0.4.0): Set a boolean parameter.
  - `name` string: Parameter name.
  - `value` boolean: Value. (Replaces the kind when the same name exists)
- `getBool(name)` (method, since 0.4.0): Get a boolean parameter.
  - `name` string: Parameter name.
  - returns boolean: Value. (False when missing or not a boolean)
- `setTrigger(name)` (method, since 0.4.0): Set a trigger. (Cleared when a transition that uses it as a condition is taken)
  - `name` string: Parameter name. (Replaces the kind when the same name exists)
- `resetTrigger(name)` (method, since 0.4.0): Clear a trigger.
  - `name` string: Parameter name. (Replaces the kind when the same name exists)
- `getTrigger(name)` (method, since 0.4.0): Get whether a trigger is set.
  - `name` string: Parameter name.
  - returns boolean: True if set. (False when missing or not a trigger)
- `getParameters()` (method, since 0.4.0): Get all parameters.
  - returns Dictionary<string, { type: string, value: number | boolean }>: Dictionary of parameter names to kinds and values. (type is float, int, bool, trigger, not a copy)
- `addState(state)` (method, since 0.4.0): Add a state. (Returns its index in the state list, it starts in the first added state)
  - `state` AnimationState: State to add.
  - returns number: Index of the added state. (from 0)
- `getStates()` (method, since 0.4.0): Returns the state list.
  - returns List<AnimationState>: List of states. (not a copy)
- `addTransition(transition)` (method, since 0.4.0): Add a transition. (Returns its index in the transition list)
  - `transition` AnimationTransition: Transition to add.
  - returns number: Index of the added transition. (From 0)
- `getTransitions()` (method, since 0.4.0): Get the transition list.
  - returns List<AnimationTransition>: Transition list. (Not a copy)
- `getCurrentStateIndex()` (method, since 0.4.0): Get the current state.
  - returns number | null: Index of the current state. (The leaving state while blending, null when there are no states)
- `getCurrentNormalizedTime()` (method, since 0.4.0): Get the normalized time of the current state.
  - returns number: Current state time divided by the length of one cycle. (0 when there are no states)
- `getCurrentFrame()` (method, since 0.4.0): Get the frame of the current state.
  - returns Frame | Rect | null: Clip frame shown at the current state time. (An entry of the clip frame list, null when there is no state, clip, or frame)
- `isInTransition()` (method, since 0.4.0): Get whether it is blending.
  - returns boolean: True while blending two states.
- `getNextStateIndex()` (method, since 0.4.0): Get the state being blended in.
  - returns number | null: Index of the entering state. (null when not blending)
- `getNextNormalizedTime()` (method, since 0.4.0): Get the normalized time of the entering state.
  - returns number: Entering state time divided by the length of one cycle. (0 when not blending)
- `getNextFrame()` (method, since 0.4.0): Get the frame of the entering state.
  - returns Frame | Rect | null: Clip frame shown at the entering state time. (null when not blending or when there is no clip or frame)
- `getTransitionWeight()` (method, since 0.4.0): Get the weight of the entering state. (Crossfade)
  - returns number: Blended time / blend time. (0 to 1, the current state's weight is 1 minus this, 0 when not blending)

## AnimationConditionMode (enum)

How a transition condition compares.
- if and ifNot look at boolean parameters. (if also looks at whether a trigger is set)
- greater, less, equals, notEqual compare float and integer parameters with the threshold.

- `if` = `if`: The boolean parameter is true or the trigger is set.
- `ifNot` = `ifNot`: The boolean parameter is false.
- `greater` = `greater`: The number parameter is greater than the threshold.
- `less` = `less`: The number parameter is less than the threshold.
- `equals` = `equals`: The number parameter equals the threshold.
- `notEqual` = `notEqual`: The number parameter differs from the threshold.
