# misc/spriteanimator (vanilla.js 0.4.0)

> https://vanillapunch.com/docs/vanilla.js/0.4.0/api/misc/spriteanimator/

Sprite animator component.

## SpriteAnimator extends Component

Sprite animator component.
- Registers named clips (frame sequences) and switches with SpriteAnimator.play(node, "run") or playClip("run").
- Playing the same clip again does not restart it. (can be changed with the restartIfSame option)
- When a clip ends, the next state can follow via the onComplete callback. (combines with an FSM)
- Applies the current frame (image + rect) to the Sprite component on the same node.
- Usage:
    const animator = node.addComponent(SpriteAnimator);
    animator.addClip("idle", image, idleRects, 10, true);
    animator.addClip("attack", image, attackRects, 12, false);
    SpriteAnimator.play(node, "attack", { onComplete: () => animator.playClip("idle") });
- Same form in both engines: the static SpriteAnimator.play(node, clipName, options) plays with the node's animator, and playClip is for when only the animator is at hand (inside the complete callback).
  (the Rust SpriteAnimator::play, play_clip)

Example: Loop an idle clip, attack once on press, then return to idle

```js
import { Engine, EngineConfiguration, Scene, WorldNode, Sprite, SpriteAnimator, ImageAsset, Rect, Vector2, Pivot } from "./build/vanilla.js";

const imageAsset = new ImageAsset();
await imageAsset.load("examples/assets/spritesheet.png");
const image = imageAsset.getImage();
const idleRects = [];
const attackRects = [];
for (let column = 0; column < 3; ++column) {
	idleRects.push(Rect.create(column * 200, 0, 200, 200));
	attackRects.push(Rect.create(column * 200, 200, 200, 200));
}

const characterNode = new WorldNode();
characterNode.addComponent(Sprite);
const spriteAnimator = characterNode.addComponent(SpriteAnimator);
spriteAnimator.addClip("idle", image, idleRects, 6, true);
spriteAnimator.addClip("attack", image, attackRects, 12, false);
spriteAnimator.playClip("idle");

class MainScene extends Scene {
	initialize(engine) {
		super.initialize(engine);
		characterNode.setPivot(Pivot.middleCenter);
		characterNode.setLocalPosition(Vector2.create(320, 180));
		characterNode.setContentSize(Vector2.create(200, 200));
		const root = this.getRoot();
		root.addChild(characterNode);
	}

	touchPress(viewInputPosition) {
		super.touchPress(viewInputPosition);
		spriteAnimator.playClip("attack", {
			onComplete: () => {
				spriteAnimator.playClip("idle");
			},
		});
	}
}

const engineConfiguration = new EngineConfiguration();
const engine = new Engine(engineConfiguration);
engine.run(new MainScene());
```

- `constructor()` (constructor, since 0.3.0): Constructor.
- `addClip(clipName, image, frameRects, fps = 10, isLoop = true)` (method, since 0.3.0): Registers a clip.
  - `clipName` string: Clip name.
  - `image` HTMLImageElement: Image to cut the frames from.
  - `frameRects` Rect[]: Area to cut from the image for each frame. (pixels)
  - `fps` number: Frames per second. (default 10)
  - `isLoop` boolean: True to loop. (default true; if false, stops on the last frame and calls onComplete)
- `addClipFromAtlas(clipName, image, atlasJson, frameIds, fps = 10, isLoop = true)` (method, since 0.3.0): Registers clips from an atlas JSON.
  - Accepts the TexturePacker format ({ frames: { name: { frame: {x,y,w,h} } } }).
  - `clipName` string: Clip name.
  - `image` HTMLImageElement: Image to cut the frames from.
  - `atlasJson` object: Atlas data in TexturePacker format.
  - `frameIds` string[]: List of frame names to use in order. (names not in the atlas are skipped)
  - `fps` number: Frames per second. (default 10)
  - `isLoop` boolean: True to loop. (default true; if false, stops on the last frame and calls onComplete)

  Example: Make a clip from frame names in an atlas JSON

  ```js
  import { SpriteAnimator, ImageAsset } from "./build/vanilla.js";
  
  const imageAsset = new ImageAsset();
  await imageAsset.load("examples/assets/spritesheet.png");
  const image = imageAsset.getImage();
  const atlasJson = {
  	frames: {
  		"run_0": { frame: { x: 0, y: 400, w: 200, h: 200 } },
  		"run_1": { frame: { x: 200, y: 400, w: 200, h: 200 } },
  		"run_2": { frame: { x: 400, y: 400, w: 200, h: 200 } },
  	},
  };
  const spriteAnimator = new SpriteAnimator();
  spriteAnimator.addClipFromAtlas("run", image, atlasJson, ["run_0", "run_1", "run_2"], 12, true);
  console.log(spriteAnimator.hasClip("run"), spriteAnimator.playClip("run"));
  spriteAnimator.tick(0.1);
  console.log(spriteAnimator.getClipName(), spriteAnimator.getCurrentFrameIndex());
  ```

- `playClip(clipName, options = {})` (method, since 0.4.0): Play with the animator. (the Rust play_clip)
  - If the same clip is already playing, it does not restart. (restarts if restartIfSame is true)
  - Puts the first frame into the Sprite on the same node right away.
  - `clipName` string: Name of the clip to play. (false if the name is not registered)
  - `options` object: { onComplete?, restartIfSame = false }
  - returns boolean: Whether playback started.
- `stop()` (method, since 0.3.0): Stop.
- `tick(timeDelta)` (method, since 0.3.0): Update.
  - `timeDelta` number: Time since the last frame. (Seconds)
- `applyCurrentFrame()` (method, since 0.3.0): Applies the current frame to the sprite.
- `findSprite()` (method, since 0.3.0): Finds the sprite on the same node. (cached once found)
  - returns Sprite | null: The first Sprite component on the same node. (null if none or not attached to a node)
- `getClipName()` (method, since 0.3.0): Returns the current clip name.
  - returns string | null: Current clip name. (null if nothing has been played)
- `isPlaying()` (method, since 0.3.0): Whether playing.
  - returns boolean: True if playing.
- `getCurrentFrameIndex()` (method, since 0.4.0): Returns the current frame number. (from 0 within the clip)
  - returns number: Current frame index. (from 0 within the clip)
- `hasClip(clipName)` (method, since 0.3.0): Whether the clip exists.
  - `clipName` string: Name of the clip to look up.
  - returns boolean: True if the clip is registered.
- `static play(node, clipName, options = {})` (static, since 0.3.0): Play with the node's animator. (static, puts the first frame into the Sprite on the same node right away, false if the node has no animator)
  - `node` object: Node with a SpriteAnimator attached.
  - `clipName` string: Name of the clip to play. (false if the name is not registered)
  - `options` object: { onComplete?, restartIfSame = false }
  - returns boolean: Whether playback started.
