트윈과 타임라인
시간에 따라 값을 바꾸는 방법을 다룹니다. 값이나 노드 속성을 시작값에서 목표값으로 옮기는 Tween, 프레임 그림을 넘기는 Animation 과 SpriteAnimator, Timeline Editor 가 저장한 문서를 재생하는 Timeline, 그리고 상태 기계인 Animator 차례입니다. 노드 자체는 "노드와 컴포넌트" 장, 3D 모델의 본 애니메이션은 "3D" 장, 편집기는 "저작 도구" 장에서 다룹니다.
Tween
Tween 은 이름 붙은 값들을 시작값에서 목표값으로 옮깁니다. 값은 숫자나 Vector2 이고, 시작값과 목표값의 꼴이 같은 이름만 바뀝니다.
new Tween(startValues)로 만들고to(endValues, duration)(초, 기본 1),delay(seconds),easing(easingFunction)(기본linear)을 잇습니다. 이 메서드들은 트윈 자신을 돌려주므로 이어 부를 수 있습니다.setUpdate((values) => {})는 매 갱신마다 이번 값 객체를 받고(대기 시간 동안은 부르지 않음),setComplete(() => {})는 진행률이 1 에 닿으면 한 번 불립니다.start(),stop(),tick(timeDelta),isFinished()로 직접 돌릴 수 있습니다.duration이 0 이하면 바로 끝으로 칩니다.
import { Tween } from "./build/vanilla.js";
const tween = new Tween({ x: 0, alpha: 1 });
tween.to({ x: 100, alpha: 0 }, 0.5);
tween.easing(Tween.easingFunction.quadratic.easeOut);
tween.setUpdate((values) => {
console.log(values.x, values.alpha);
});
tween.setComplete(() => {
console.log("complete");
});
tween.start();
for (let step = 0; step < 5; ++step) {
tween.tick(0.1);
}
console.log(tween.isFinished());이징
Tween.easingFunction 에 linear 와 quadratic, cubic, quartic, quintic, sinusoidal, exponential, circular, elastic, back, bounce 가 있고, linear 를 뺀 것은 저마다 easeIn, easeOut, easeInOut 을 가집니다(Tween.easingFunction.back.easeOut 처럼). 진행률(0 ~ 1)을 받아 바뀐 진행률을 돌려주는 함수면 무엇이든 easing 에 줄 수 있습니다.
노드 속성 트윈
setTarget(node) 로 대상 노드를 정하면 값 이름이 TweenProperty 의 이름인 값을 매 갱신마다 그 노드에 바로 씁니다.
TweenProperty |
값 | 쓰는 곳 |
|---|---|---|
localPosition |
Vector2 |
setLocalPosition |
localScale |
Vector2 |
setLocalScale |
localRotation |
숫자 (도) | setLocalRotation |
localOpacity |
숫자 (0 ~ 1) | setLocalOpacity |
contentSize |
Vector2 (픽셀) |
setContentSize |
Vector2 속성에 숫자를 주면 두 축에 같이 씁니다(localScale: 0 은 (0, 0)). Tween.createNodeTween(node, tweenProperty, startValue, endValue, duration) 은 속성 하나를 움직이는 트윈을 한 줄로 만듭니다. 노드에 값 하나만 쓰고 싶으면 applyTweenProperty(node, tweenProperty, value) 를 씁니다.
씬에서는 scene.startTween(tween) 으로 맡깁니다. 씬이 트윈을 시작하고 매 프레임 갱신하며, 끝나면 목록에서 뺍니다. stopTween(tween), stopAllTweens(), getTweenCount() 도 있습니다.
import { Engine, EngineConfiguration, Scene, WorldNode, Paint, Tween, TweenProperty, Vector2, Color } from "./build/vanilla.js";
class TweenScene extends Scene {
#boxNode;
constructor() {
super();
this.#boxNode = null;
}
async load(engine) {
await super.load(engine);
const boxNode = new WorldNode();
boxNode.setContentSize(Vector2.create(80, 80));
boxNode.setLocalPosition(Vector2.create(160, 360));
const paint = boxNode.addComponent(Paint);
paint.setColor(new Color(0.35, 0.8, 1, 1));
paint.setRoundSize(12);
const root = this.getRoot();
root.addChild(boxNode);
this.#boxNode = boxNode;
}
initialize(engine) {
super.initialize(engine);
const boxNode = this.#boxNode;
const moveTween = new Tween({ localPosition: Vector2.create(160, 360), localOpacity: 0 });
moveTween.to({ localPosition: Vector2.create(1120, 360), localOpacity: 1 }, 1.5);
moveTween.delay(0.2);
moveTween.easing(Tween.easingFunction.cubic.easeInOut);
moveTween.setTarget(boxNode);
moveTween.setComplete(() => {
this.startPulse(1, 1.4);
});
this.startTween(moveTween);
}
startPulse(startScale, endScale) {
const pulseTween = Tween.createNodeTween(this.#boxNode, TweenProperty.localScale, startScale, endScale, 0.4);
pulseTween.easing(Tween.easingFunction.sinusoidal.easeInOut);
pulseTween.setComplete(() => {
this.startPulse(endScale, startScale);
});
this.startTween(pulseTween);
}
}
const engineConfiguration = new EngineConfiguration();
engineConfiguration.referenceResolutionSize = Vector2.create(1280, 720);
const engine = new Engine(engineConfiguration);
engine.run(new TweenScene());대상 노드가 트윈이 처음 돈 때의 노드 트리에서 떨어지면(removeChild 같은 것) 트윈은 완료 알림 없이 조용히 끝납니다.
Animation 과 Frame
Frame 은 그림 하나와 그 안의 영역(Rect)입니다. new Frame(image, rect) 로 만들고 영역을 주지 않으면 그림 전체입니다. Sprite.setFrame(frame) 은 그림과 영역을 함께 겁니다.
Animation 은 프레임 목록을 정해진 빠르기로 넘기는 처리기입니다. 노드에 붙는 컴포넌트가 아니므로 tick 을 직접 부르고, 지금 프레임을 읽어 그립니다.
- 프레임은
setFrames(frames),setFramesFromRects(image, rects)(스프라이트 시트,image는HTMLImageElement),setFramesFromImages(images)(낱장 그림) 로 넣습니다. 넣으면 첫 프레임으로 돌아가 멈춥니다. setAnimationSpeed(framesPerSecond)는 초당 넘기는 프레임 수입니다(기본 10).setLoop(isLoop)(기본true),setOnComplete(callback)(반복하지 않을 때 끝에 닿으면 불림).play(),pause()(지금 프레임에 멈춤),resume(),stop()(첫 프레임으로),gotoAndPlay(index),gotoAndStop(index).getCurrentFrame(),getCurrentFrameIndex(),getTotalFrameCount(),isPlaying().
import { Engine, EngineConfiguration, Scene, WorldNode, Sprite, ImageAsset, Animation, Vector2, Rect } from "./build/vanilla.js";
class AnimationScene extends Scene {
#animation;
#sprite;
constructor() {
super();
this.#animation = new Animation();
this.#sprite = null;
}
async load(engine) {
await super.load(engine);
const imageAsset = new ImageAsset();
await imageAsset.load("examples/assets/spritesheet.png");
const image = imageAsset.getImage();
const rects = [];
for (let index = 0; index < 8; ++index) {
const column = index % 3;
const row = Math.floor(index / 3);
rects.push(Rect.create(column * 200, row * 200, 200, 200));
}
const animation = this.#animation;
animation.setFramesFromRects(image, rects);
animation.setAnimationSpeed(8);
animation.setLoop(true);
animation.play();
const node = new WorldNode();
node.setContentSize(Vector2.create(200, 200));
node.setLocalPosition(Vector2.create(640, 360));
this.#sprite = node.addComponent(Sprite);
const root = this.getRoot();
root.addChild(node);
}
tick(timeDelta) {
super.tick(timeDelta);
const animation = this.#animation;
animation.tick(timeDelta);
const currentFrame = animation.getCurrentFrame();
this.#sprite.setFrame(currentFrame);
}
}
const engineConfiguration = new EngineConfiguration();
engineConfiguration.referenceResolutionSize = Vector2.create(1280, 720);
const engine = new Engine(engineConfiguration);
engine.run(new AnimationScene());SpriteAnimator
SpriteAnimator 는 이름 붙은 클립(프레임 차례)을 등록해 두고 play("run") 처럼 바꾸는 컴포넌트입니다. 매 프레임 같은 노드의 Sprite 에 지금 프레임을 걸어 줍니다. 그래서 노드에 Sprite 를 먼저 붙여 둡니다.
addClip(clipName, image, frameRects, framesPerSecond, isLoop)는 클립을 등록합니다(기본 10 프레임, 반복).image는HTMLImageElement입니다.addClipFromAtlas(clipName, image, atlasJson, frameIds, framesPerSecond, isLoop)는 TexturePacker 꼴({ frames: { 이름: { frame: { x, y, w, h } } } }) 표에서 프레임을 뽑습니다.play(clipName, { restartIfSame, onComplete })는 클립을 바꿉니다. 같은 클립이 이미 돌고 있으면 다시 시작하지 않고(restartIfSame: true면 다시 시작) 완료 함수만 바꿉니다. 시작했으면true를 돌려줍니다.stop(),getClipName(),isPlaying(),getCurrentFrameIndex(),hasClip(clipName), 정적SpriteAnimator.play(node, clipName, options)(노드의 애니메이터로 틀기, 러스트 판과 같은 꼴)와playClip(clipName, options)(러스트 판play_clip)가 있습니다.
import { Engine, EngineConfiguration, Scene, WorldNode, Sprite, SpriteAnimator, ImageAsset, Vector2, Rect } from "./build/vanilla.js";
class AnimatorScene extends Scene {
#spriteAnimator;
constructor() {
super();
this.#spriteAnimator = null;
}
async load(engine) {
await super.load(engine);
const imageAsset = new ImageAsset();
await imageAsset.load("examples/assets/spritesheet.png");
const image = imageAsset.getImage();
const idleRects = [Rect.create(0, 0, 200, 200), Rect.create(200, 0, 200, 200)];
const attackRects = [];
for (let column = 0; column < 3; ++column) {
attackRects.push(Rect.create(column * 200, 200, 200, 200));
}
const node = new WorldNode();
node.setContentSize(Vector2.create(200, 200));
node.setLocalPosition(Vector2.create(640, 360));
node.addComponent(Sprite);
const spriteAnimator = node.addComponent(SpriteAnimator);
spriteAnimator.addClip("idle", image, idleRects, 4, true);
spriteAnimator.addClip("attack", image, attackRects, 12, false);
spriteAnimator.playClip("idle");
const root = this.getRoot();
root.addChild(node);
this.#spriteAnimator = spriteAnimator;
}
touchPress(viewInputPosition) {
super.touchPress(viewInputPosition);
const spriteAnimator = this.#spriteAnimator;
spriteAnimator.playClip("attack", {
restartIfSame: true,
onComplete: () => {
spriteAnimator.playClip("idle");
},
});
}
}
const engineConfiguration = new EngineConfiguration();
engineConfiguration.referenceResolutionSize = Vector2.create(1280, 720);
const engine = new Engine(engineConfiguration);
engine.run(new AnimatorScene());Timeline
Timeline 은 Timeline Editor 가 저장한 문서(*.timeline.json)를 재생합니다. 문서는 무대 노드 목록, 트랙(대상 이름, 속성, 키), 마커로 이루어진 JSON 입니다.

{
"name": "Title Reveal",
"duration": 5,
"frameRate": 30,
"loop": true,
"stage": {
"width": 960,
"height": 540,
"backgroundColor": "#101114ff",
"nodes": [
{ "name": "Logo", "type": "text", "parent": null, "x": 480, "y": 270, "text": "LOGO", "fontSize": 64 }
]
},
"tracks": [
{ "target": "Logo", "property": "opacity", "keys": [
{ "time": 0, "value": 0, "easing": "cubic.out" },
{ "time": 1, "value": 1, "easing": "linear" }
] },
{ "target": "Logo", "property": "event", "keys": [{ "time": 1, "value": "shine", "easing": "step" }] }
],
"markers": [{ "time": 0.5, "name": "hit" }]
}만들기와 무대 짓기
await Timeline.loadFromUrl(url)은 주소에서 받아 만듭니다.Timeline.loadFromText(text)는 JSON 글에서,Timeline.createFromJsonAsset(jsonAsset)은 읽은JsonAsset에서 만듭니다(아직 안 읽혔으면null).new Timeline(description)은 문서 객체를 그대로 씁니다. 문서 없이 만들면 3 초, 30 프레임, 반복, 960 x 540 무대의 빈 문서입니다.buildStage(parentNode, imageResolver)는 문서의 무대 노드를 만들어parentNode아래에 붙이고, 이름에서 노드로 가는Map을 돌려줍니다. 노드 종류는group(빈 노드),paint(Paint),sprite(ShaderSprite, 격자로 자른 프레임과 효과),text(Text),particle(ParticleSystem),sound입니다.imageResolver는 문서의 그림 이름을 받아HTMLImageElement를 돌려주는 함수입니다.- 무대를 직접 지었으면
bind(rootNode)로 트랙의 대상 이름과 같은 이름의 노드를 찾아 붙입니다.setTarget(name, target)으로 하나씩 붙이거나,setTargetResolver((name) => target)로 이름을 객체로 바꾸는 함수를 줍니다. - 사운드 노드를 쓰려면
Timeline.setAudioManager(engine.getAudioManager())를 한 번 불러 둡니다.
재생
play(),pause(),stop()(처음으로, 소리와 파티클도 멈춤),seek(time)(그 시각의 값을 바로 적용, 이벤트는 내지 않음).tick(timeDelta)를 매 프레임 직접 부릅니다. 시간을 흘리고 값을 적용하며, 지나친 이벤트 키와 마커를 알립니다.setSpeed(speed)(1 이 실시간),setLoop(isLoop),getTime(),getDuration(),getFrameRate(),isPlaying(),isLoop().- 처리기:
setEventHandler((targetName, eventName, key, timeline) => {}),setMarkerHandler((markerName, marker, timeline) => {}),setCompleteHandler((timeline) => {})(반복이 아닐 때 끝에 닿으면).
트랙과 키
- 키의
easing은 그 키부터 다음 키까지 구간에 걸립니다. 이름은TIMELINE_EASING_NAMES에 있고,"linear","step","bezier"(키의curve: [x1, y1, x2, y2], CSScubic-bezier와 같은 제어점), 그리고"cubic.out"처럼<종류>.<in|out|inOut>입니다. 모르는 이름은linear로 칩니다.resolveTimelineEasing(name, curve)와createBezierEasing(x1, y1, x2, y2)로 같은 함수를 꺼낼 수 있습니다. - 노드 속성은
TIMELINE_PROPERTY_DEFINITIONS에 있습니다:x,y,width,height,scaleX,scaleY,rotation,opacity,visible,color,text,number,fontSize,visibleCharacters,frame,effect,event. 숫자는 이징으로 보간하고, 색("#rrggbbaa")은 채널마다 보간하며, 글과 참거짓은 계단으로 바뀝니다. - 이 목록에 없는 속성은 대상의
setTimelineProperty(name, value)를 부릅니다. 대상이 노드가 아니어도 이 메서드만 있으면 됩니다(ScreenEffect가 그렇습니다. "파티클" 장). - 속성이
event인 트랙은 키의 값을 이벤트 이름으로 알립니다. 대상이 파티클 노드면"play","stop","clear","emit:N"(N 개 뿜기, 없으면 30)을, 사운드 노드면"play","loop","stop"을 스스로 처리하고, 그 뒤 이벤트 처리기도 부릅니다.
아래는 examples/timelineshowcase 의 로고 문서를 재생하는 씬입니다. 문서가 쓰는 그림 emblem.png 를 먼저 받아 두고 buildStage 에 넘깁니다.
import { Engine, EngineConfiguration, Scene, Timeline, ImageAsset, Vector2 } from "./build/vanilla.js";
class TimelineScene extends Scene {
#timeline;
constructor() {
super();
this.#timeline = null;
}
async load(engine) {
await super.load(engine);
const emblemAsset = new ImageAsset();
await emblemAsset.load("examples/timelineshowcase/assets/emblem.png");
const timeline = await Timeline.loadFromUrl("examples/timelineshowcase/assets/logo.timeline.json");
const root = this.getRoot();
timeline.buildStage(root, (imageName) => {
if (imageName === "emblem.png") {
return emblemAsset.getImage();
}
return null;
});
timeline.setMarkerHandler((markerName) => {
console.log("marker", markerName);
});
timeline.setEventHandler((targetName, eventName) => {
console.log("event", targetName, eventName);
});
timeline.play();
this.#timeline = timeline;
}
tick(timeDelta) {
super.tick(timeDelta);
this.#timeline.tick(timeDelta);
}
}
const engineConfiguration = new EngineConfiguration();
engineConfiguration.referenceResolutionSize = Vector2.create(960, 540);
const engine = new Engine(engineConfiguration);
engine.run(new TimelineScene());문서를 코드로 만들어 이미 있는 노드에 붙일 수도 있습니다. 아래는 이름이 Box 인 노드를 좌우로 옮기며 색을 바꾸고, 1 초에 이벤트를, 0.5 초에 마커를 냅니다.
import { Engine, EngineConfiguration, Scene, WorldNode, Paint, Timeline, Vector2, Color } from "./build/vanilla.js";
const timeline = new Timeline({
name: "Box",
duration: 2,
frameRate: 30,
loop: true,
stage: { width: 640, height: 360, backgroundColor: "#101114ff", nodes: [] },
tracks: [
{ target: "Box", property: "x", keys: [
{ time: 0, value: 120, easing: "cubic.inOut" },
{ time: 1, value: 520, easing: "cubic.inOut" },
{ time: 2, value: 120, easing: "linear" },
] },
{ target: "Box", property: "color", keys: [
{ time: 0, value: "#3b82f6ff", easing: "linear" },
{ time: 1, value: "#f97316ff", easing: "linear" },
{ time: 2, value: "#3b82f6ff", easing: "linear" },
] },
{ target: "Box", property: "event", keys: [
{ time: 1, value: "bounce", easing: "step" },
] },
],
markers: [{ time: 0.5, name: "half" }],
});
class BindScene extends Scene {
async load(engine) {
await super.load(engine);
const boxNode = new WorldNode();
boxNode.setName("Box");
boxNode.setContentSize(Vector2.create(64, 64));
boxNode.setLocalPosition(Vector2.create(120, 180));
const paint = boxNode.addComponent(Paint);
paint.setColor(new Color(1, 1, 1, 1));
const root = this.getRoot();
root.addChild(boxNode);
timeline.bind(root);
timeline.setEventHandler((targetName, eventName) => {
console.log(targetName, eventName);
});
timeline.setMarkerHandler((markerName) => {
console.log(markerName);
});
timeline.play();
}
tick(timeDelta) {
super.tick(timeDelta);
timeline.tick(timeDelta);
}
}
const engineConfiguration = new EngineConfiguration();
engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
const engine = new Engine(engineConfiguration);
engine.run(new BindScene());Animator
Animator, AnimationState, AnimationTransition, AnimationClip 은 상태마다 프레임 클립을 달고, 매개변수 조건으로 상태를 옮기며 두 상태를 섞는 상태 기계입니다. (유니티 Animator 의 상태 기계와 같은 뼈대)
animator.addState(state)와addTransition(transition)은 목록에 넣고 번호를 돌려줍니다.getStates(),getTransitions()는 엔진의List를 돌려줍니다. 처음 더한 상태에서 시작합니다.AnimationState는 클립(setClip), 속도(setSpeed), 되풀이(setLoop,null이면 클립을 따름)를 담습니다.AnimationTransition은setFrom(stateIndex),setTo(stateIndex)로 두 상태를 잇습니다.setFrom(null)이면 어느 상태에서나 탑니다(Any State).addCondition(이름, AnimationConditionMode, 기준 값)으로 조건을 더하고,setExitTime(정규화 시간)이면 그 시각을 지날 때만,setDuration(초)동안 두 상태를 섞습니다.- 매개변수는
setFloat,setInteger,setBool,setTrigger로 넣습니다. 조건에 쓴 트리거는 전이를 타면 풀립니다. animator.tick(timeDelta)가 상태 시간을 흘리고, Any State 전이부터 넣은 차례로 보아 처음 맞는 하나를 탑니다. 섞는 동안에는 새 전이를 보지 않습니다.- 고른 프레임은
getCurrentFrame(), 섞는 중이면getNextFrame()과getTransitionWeight()로 읽습니다. AnimationClip은 프레임 영역 목록, 길이(초), 반복 여부를 담습니다.AnimationClip.fromAtlas(atlasJson, frameIds, framesPerSecond, isLoop)는 아틀라스 표에서 영역을 뽑고 길이를 프레임 수 나누기 초당 프레임 수로 정합니다.
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 = AnimationClip.fromAtlas({ frames: { run0: { frame: { x: 0, y: 32, w: 32, h: 32 } }, run1: { frame: { x: 32, y: 32, w: 32, h: 32 } } } }, ["run0", "run1"], 4, 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.25);
const frame = animator.getCurrentFrame();
console.log(animator.getCurrentStateIndex(), animator.isInTransition(), frame.position.y);Animator 는 프레임 영역만 고르고 그리지 않으므로, 고른 영역은 게임이 Sprite 에 겁니다. 캐릭터의 상태에 따라 클립만 바꾸는 간단한 일은 FiniteStateMachine 과 SpriteAnimator 를 함께 써도 됩니다. 상태의 enter 에서 play 를 부르는 식입니다.
import { Engine, EngineConfiguration, Scene, WorldNode, Sprite, SpriteAnimator, FiniteStateMachine, ImageAsset, Vector2, Rect } from "./build/vanilla.js";
class StateScene extends Scene {
#stateMachine;
constructor() {
super();
this.#stateMachine = new FiniteStateMachine();
}
async load(engine) {
await super.load(engine);
const imageAsset = new ImageAsset();
await imageAsset.load("examples/assets/spritesheet.png");
const image = imageAsset.getImage();
const node = new WorldNode();
node.setContentSize(Vector2.create(200, 200));
node.setLocalPosition(Vector2.create(640, 360));
node.addComponent(Sprite);
const spriteAnimator = node.addComponent(SpriteAnimator);
spriteAnimator.addClip("idle", image, [Rect.create(0, 0, 200, 200), Rect.create(200, 0, 200, 200)], 4, true);
spriteAnimator.addClip("run", image, [Rect.create(0, 200, 200, 200), Rect.create(200, 200, 200, 200), Rect.create(400, 200, 200, 200)], 10, true);
const root = this.getRoot();
root.addChild(node);
const stateMachine = this.#stateMachine;
stateMachine.addState("idle", {
enter: () => {
spriteAnimator.playClip("idle");
},
tick: (timeDelta, stateSeconds) => {
if (stateSeconds >= 2) {
stateMachine.changeState("run");
}
},
});
stateMachine.addState("run", {
enter: () => {
spriteAnimator.playClip("run");
},
tick: (timeDelta, stateSeconds) => {
if (stateSeconds >= 1) {
stateMachine.changeState("idle");
}
},
});
stateMachine.changeState("idle");
}
tick(timeDelta) {
super.tick(timeDelta);
this.#stateMachine.tick(timeDelta);
}
}
const engineConfiguration = new EngineConfiguration();
engineConfiguration.referenceResolutionSize = Vector2.create(1280, 720);
const engine = new Engine(engineConfiguration);
engine.run(new StateScene());주의할 점
Animation,Timeline,FiniteStateMachine은 스스로 시간이 가지 않습니다. 씬의tick에서tick(timeDelta)를 불러 줍니다. 트윈은scene.startTween으로 맡기면 씬이 갱신합니다.setFramesFromRects와addClip의 그림은HTMLImageElement여야 합니다.ImageAsset이면getImage()로 꺼내 넘깁니다(setFramesFromRects는 다른 것을 받으면 아무것도 하지 않습니다).SpriteAnimator는 같은 노드의Sprite를 찾아 씁니다.Sprite가 없으면 그림이 바뀌지 않습니다.Timeline.seek는 이벤트와 마커를 내지 않습니다. 이벤트는tick이 시간을 지나갈 때만 납니다.Timeline.loadFromUrl은 받은 응답의 상태를 따로 보지 않고 JSON 으로 읽습니다. 주소가 틀리면 JSON 해석 오류로 실패합니다.
관련 클래스
Tween, TweenProperty, Frame, Animation, Sprite, SpriteAnimator, Timeline, ShaderSprite, ParticleSystem, ScreenEffect, Animator, AnimationState, AnimationTransition, AnimationClip, FiniteStateMachine, Scene
Tweens and Timelines
This chapter covers changing values over time. It goes through Tween, which moves values or node properties from a start value to a target value; Animation and SpriteAnimator, which flip through frame images; Timeline, which plays documents saved by the Timeline Editor; and Animator, a state machine. Nodes themselves are covered in the "Nodes and Components" chapter, bone animation of 3D models in the "3D" chapter, and the editor in the "Authoring Tools" chapter.
Tween
Tween moves named values from start values to target values. Values are numbers or Vector2, and only names whose start and target values have the same type change.
- Create one with
new Tween(startValues)and chainto(endValues, duration)(seconds, default 1),delay(seconds), andeasing(easingFunction)(defaultlinear). These methods return the tween itself, so they can be chained. setUpdate((values) => {})receives the current value object on every update (not during the delay), andsetComplete(() => {})is called once when progress reaches 1.- You can drive it yourself with
start(),stop(),tick(timeDelta), andisFinished(). Adurationof 0 or less counts as finished immediately.
import { Tween } from "./build/vanilla.js";
const tween = new Tween({ x: 0, alpha: 1 });
tween.to({ x: 100, alpha: 0 }, 0.5);
tween.easing(Tween.easingFunction.quadratic.easeOut);
tween.setUpdate((values) => {
console.log(values.x, values.alpha);
});
tween.setComplete(() => {
console.log("complete");
});
tween.start();
for (let step = 0; step < 5; ++step) {
tween.tick(0.1);
}
console.log(tween.isFinished());Easing
Tween.easingFunction has linear plus quadratic, cubic, quartic, quintic, sinusoidal, exponential, circular, elastic, back, and bounce, and every one except linear has easeIn, easeOut, and easeInOut (as in Tween.easingFunction.back.easeOut). Any function that takes progress (0 to 1) and returns changed progress can be passed to easing.
Node property tweens
After setting a target node with setTarget(node), values whose names are TweenProperty names are written straight to that node on every update.
TweenProperty |
Value | Written with |
|---|---|---|
localPosition |
Vector2 |
setLocalPosition |
localScale |
Vector2 |
setLocalScale |
localRotation |
Number (degrees) | setLocalRotation |
localOpacity |
Number (0 to 1) | setLocalOpacity |
contentSize |
Vector2 (pixels) |
setContentSize |
Giving a number to a Vector2 property writes it to both axes (localScale: 0 is (0, 0)). Tween.createNodeTween(node, tweenProperty, startValue, endValue, duration) creates a tween that moves one property in a single line. To write just one value to a node, use applyTweenProperty(node, tweenProperty, value).
In a scene, hand tweens over with scene.startTween(tween). The scene starts the tween, updates it every frame, and removes it when finished. There are also stopTween(tween), stopAllTweens(), and getTweenCount().
import { Engine, EngineConfiguration, Scene, WorldNode, Paint, Tween, TweenProperty, Vector2, Color } from "./build/vanilla.js";
class TweenScene extends Scene {
#boxNode;
constructor() {
super();
this.#boxNode = null;
}
async load(engine) {
await super.load(engine);
const boxNode = new WorldNode();
boxNode.setContentSize(Vector2.create(80, 80));
boxNode.setLocalPosition(Vector2.create(160, 360));
const paint = boxNode.addComponent(Paint);
paint.setColor(new Color(0.35, 0.8, 1, 1));
paint.setRoundSize(12);
const root = this.getRoot();
root.addChild(boxNode);
this.#boxNode = boxNode;
}
initialize(engine) {
super.initialize(engine);
const boxNode = this.#boxNode;
const moveTween = new Tween({ localPosition: Vector2.create(160, 360), localOpacity: 0 });
moveTween.to({ localPosition: Vector2.create(1120, 360), localOpacity: 1 }, 1.5);
moveTween.delay(0.2);
moveTween.easing(Tween.easingFunction.cubic.easeInOut);
moveTween.setTarget(boxNode);
moveTween.setComplete(() => {
this.startPulse(1, 1.4);
});
this.startTween(moveTween);
}
startPulse(startScale, endScale) {
const pulseTween = Tween.createNodeTween(this.#boxNode, TweenProperty.localScale, startScale, endScale, 0.4);
pulseTween.easing(Tween.easingFunction.sinusoidal.easeInOut);
pulseTween.setComplete(() => {
this.startPulse(endScale, startScale);
});
this.startTween(pulseTween);
}
}
const engineConfiguration = new EngineConfiguration();
engineConfiguration.referenceResolutionSize = Vector2.create(1280, 720);
const engine = new Engine(engineConfiguration);
engine.run(new TweenScene());If the target node leaves the node tree it was in when the tween first ran (through removeChild and the like), the tween ends quietly without the completion callback.
Animation and Frame
A Frame is one image and a region (Rect) inside it. Create one with new Frame(image, rect); without a region it is the whole image. Sprite.setFrame(frame) sets the image and region together.
Animation is a processor that flips through a list of frames at a set speed. It is not a component attached to a node, so you call tick yourself and read the current frame to draw it.
- Frames are set with
setFrames(frames),setFramesFromRects(image, rects)(sprite sheet;imageis anHTMLImageElement), orsetFramesFromImages(images)(separate images). Setting them returns to the first frame and stops. setAnimationSpeed(framesPerSecond)is the number of frames per second (default 10).setLoop(isLoop)(defaulttrue) andsetOnComplete(callback)(called when it reaches the end without looping).play(),pause()(stops on the current frame),resume(),stop()(back to the first frame),gotoAndPlay(index), andgotoAndStop(index).getCurrentFrame(),getCurrentFrameIndex(),getTotalFrameCount(), andisPlaying().
import { Engine, EngineConfiguration, Scene, WorldNode, Sprite, ImageAsset, Animation, Vector2, Rect } from "./build/vanilla.js";
class AnimationScene extends Scene {
#animation;
#sprite;
constructor() {
super();
this.#animation = new Animation();
this.#sprite = null;
}
async load(engine) {
await super.load(engine);
const imageAsset = new ImageAsset();
await imageAsset.load("examples/assets/spritesheet.png");
const image = imageAsset.getImage();
const rects = [];
for (let index = 0; index < 8; ++index) {
const column = index % 3;
const row = Math.floor(index / 3);
rects.push(Rect.create(column * 200, row * 200, 200, 200));
}
const animation = this.#animation;
animation.setFramesFromRects(image, rects);
animation.setAnimationSpeed(8);
animation.setLoop(true);
animation.play();
const node = new WorldNode();
node.setContentSize(Vector2.create(200, 200));
node.setLocalPosition(Vector2.create(640, 360));
this.#sprite = node.addComponent(Sprite);
const root = this.getRoot();
root.addChild(node);
}
tick(timeDelta) {
super.tick(timeDelta);
const animation = this.#animation;
animation.tick(timeDelta);
const currentFrame = animation.getCurrentFrame();
this.#sprite.setFrame(currentFrame);
}
}
const engineConfiguration = new EngineConfiguration();
engineConfiguration.referenceResolutionSize = Vector2.create(1280, 720);
const engine = new Engine(engineConfiguration);
engine.run(new AnimationScene());SpriteAnimator
SpriteAnimator is a component that registers named clips (frame sequences) and switches between them with calls like play("run"). Every frame it sets the current frame on the Sprite of the same node, so attach a Sprite to the node first.
addClip(clipName, image, frameRects, framesPerSecond, isLoop)registers a clip (default 10 frames per second, looping).imageis anHTMLImageElement.addClipFromAtlas(clipName, image, atlasJson, frameIds, framesPerSecond, isLoop)takes frames from a TexturePacker-style table ({ frames: { name: { frame: { x, y, w, h } } } }).play(clipName, { restartIfSame, onComplete })switches clips. If the same clip is already playing, it does not restart (unlessrestartIfSame: true) and only replaces the completion function. It returnstrueif it started the clip.- There are also
stop(),getClipName(),isPlaying(),getCurrentFrameIndex(),hasClip(clipName), the staticSpriteAnimator.play(node, clipName, options)(plays with the node's animator, the same form as the Rust engine), andplayClip(clipName, options)(the Rustplay_clip).
import { Engine, EngineConfiguration, Scene, WorldNode, Sprite, SpriteAnimator, ImageAsset, Vector2, Rect } from "./build/vanilla.js";
class AnimatorScene extends Scene {
#spriteAnimator;
constructor() {
super();
this.#spriteAnimator = null;
}
async load(engine) {
await super.load(engine);
const imageAsset = new ImageAsset();
await imageAsset.load("examples/assets/spritesheet.png");
const image = imageAsset.getImage();
const idleRects = [Rect.create(0, 0, 200, 200), Rect.create(200, 0, 200, 200)];
const attackRects = [];
for (let column = 0; column < 3; ++column) {
attackRects.push(Rect.create(column * 200, 200, 200, 200));
}
const node = new WorldNode();
node.setContentSize(Vector2.create(200, 200));
node.setLocalPosition(Vector2.create(640, 360));
node.addComponent(Sprite);
const spriteAnimator = node.addComponent(SpriteAnimator);
spriteAnimator.addClip("idle", image, idleRects, 4, true);
spriteAnimator.addClip("attack", image, attackRects, 12, false);
spriteAnimator.playClip("idle");
const root = this.getRoot();
root.addChild(node);
this.#spriteAnimator = spriteAnimator;
}
touchPress(viewInputPosition) {
super.touchPress(viewInputPosition);
const spriteAnimator = this.#spriteAnimator;
spriteAnimator.playClip("attack", {
restartIfSame: true,
onComplete: () => {
spriteAnimator.playClip("idle");
},
});
}
}
const engineConfiguration = new EngineConfiguration();
engineConfiguration.referenceResolutionSize = Vector2.create(1280, 720);
const engine = new Engine(engineConfiguration);
engine.run(new AnimatorScene());Timeline
Timeline plays documents (*.timeline.json) saved by the Timeline Editor. A document is JSON made of a list of stage nodes, tracks (target name, property, keys), and markers.

{
"name": "Title Reveal",
"duration": 5,
"frameRate": 30,
"loop": true,
"stage": {
"width": 960,
"height": 540,
"backgroundColor": "#101114ff",
"nodes": [
{ "name": "Logo", "type": "text", "parent": null, "x": 480, "y": 270, "text": "LOGO", "fontSize": 64 }
]
},
"tracks": [
{ "target": "Logo", "property": "opacity", "keys": [
{ "time": 0, "value": 0, "easing": "cubic.out" },
{ "time": 1, "value": 1, "easing": "linear" }
] },
{ "target": "Logo", "property": "event", "keys": [{ "time": 1, "value": "shine", "easing": "step" }] }
],
"markers": [{ "time": 0.5, "name": "hit" }]
}Creating and building the stage
await Timeline.loadFromUrl(url)fetches a document from a URL and creates a timeline.Timeline.loadFromText(text)creates one from JSON text, andTimeline.createFromJsonAsset(jsonAsset)from a loadedJsonAsset(nullif not loaded yet).new Timeline(description)uses a document object as is. Created without a document, it is an empty document of 3 seconds, 30 frames per second, looping, with a 960 x 540 stage.buildStage(parentNode, imageResolver)creates the document's stage nodes, adds them underparentNode, and returns aMapfrom names to nodes. Node types aregroup(empty node),paint(Paint),sprite(ShaderSprite, with grid-cut frames and effects),text(Text),particle(ParticleSystem), andsound.imageResolveris a function that takes an image name from the document and returns anHTMLImageElement.- If you built the stage yourself,
bind(rootNode)finds and attaches nodes whose names match the tracks' target names. Attach them one by one withsetTarget(name, target), or give a function that turns names into objects withsetTargetResolver((name) => target). - To use sound nodes, call
Timeline.setAudioManager(engine.getAudioManager())once.
Playback
play(),pause(),stop()(back to the start, also stopping sounds and particles), andseek(time)(applies the values at that time immediately, without firing events).- Call
tick(timeDelta)yourself every frame. It advances time, applies values, and reports the event keys and markers it passed. setSpeed(speed)(1 is real time),setLoop(isLoop),getTime(),getDuration(),getFrameRate(),isPlaying(), andisLoop().- Handlers:
setEventHandler((targetName, eventName, key, timeline) => {}),setMarkerHandler((markerName, marker, timeline) => {}), andsetCompleteHandler((timeline) => {})(when it reaches the end without looping).
Tracks and keys
- A key's
easingapplies to the span from that key to the next. Names are inTIMELINE_EASING_NAMES:"linear","step","bezier"(uses the key'scurve: [x1, y1, x2, y2], the same control points as CSScubic-bezier), and<family>.<in|out|inOut>such as"cubic.out". Unknown names count aslinear.resolveTimelineEasing(name, curve)andcreateBezierEasing(x1, y1, x2, y2)give you the same functions. - Node properties are in
TIMELINE_PROPERTY_DEFINITIONS:x,y,width,height,scaleX,scaleY,rotation,opacity,visible,color,text,number,fontSize,visibleCharacters,frame,effect, andevent. Numbers are interpolated with easing, colors ("#rrggbbaa") per channel, and text and booleans change in steps. - Properties not in this list call the target's
setTimelineProperty(name, value). The target does not have to be a node as long as it has this method (ScreenEffectdoes; see the "Particles" chapter). - A track whose property is
eventreports key values as event names. If the target is a particle node, it handles"play","stop","clear", and"emit:N"(emit N, or 30 if omitted) itself; if it is a sound node,"play","loop", and"stop"; and then it also calls the event handler.
Below is a scene that plays the logo document from examples/timelineshowcase. It loads emblem.png, the image the document uses, first and passes it to buildStage.
import { Engine, EngineConfiguration, Scene, Timeline, ImageAsset, Vector2 } from "./build/vanilla.js";
class TimelineScene extends Scene {
#timeline;
constructor() {
super();
this.#timeline = null;
}
async load(engine) {
await super.load(engine);
const emblemAsset = new ImageAsset();
await emblemAsset.load("examples/timelineshowcase/assets/emblem.png");
const timeline = await Timeline.loadFromUrl("examples/timelineshowcase/assets/logo.timeline.json");
const root = this.getRoot();
timeline.buildStage(root, (imageName) => {
if (imageName === "emblem.png") {
return emblemAsset.getImage();
}
return null;
});
timeline.setMarkerHandler((markerName) => {
console.log("marker", markerName);
});
timeline.setEventHandler((targetName, eventName) => {
console.log("event", targetName, eventName);
});
timeline.play();
this.#timeline = timeline;
}
tick(timeDelta) {
super.tick(timeDelta);
this.#timeline.tick(timeDelta);
}
}
const engineConfiguration = new EngineConfiguration();
engineConfiguration.referenceResolutionSize = Vector2.create(960, 540);
const engine = new Engine(engineConfiguration);
engine.run(new TimelineScene());You can also create a document in code and attach it to existing nodes. The example below moves a node named Box left and right while changing its color, fires an event at 1 second, and a marker at 0.5 seconds.
import { Engine, EngineConfiguration, Scene, WorldNode, Paint, Timeline, Vector2, Color } from "./build/vanilla.js";
const timeline = new Timeline({
name: "Box",
duration: 2,
frameRate: 30,
loop: true,
stage: { width: 640, height: 360, backgroundColor: "#101114ff", nodes: [] },
tracks: [
{ target: "Box", property: "x", keys: [
{ time: 0, value: 120, easing: "cubic.inOut" },
{ time: 1, value: 520, easing: "cubic.inOut" },
{ time: 2, value: 120, easing: "linear" },
] },
{ target: "Box", property: "color", keys: [
{ time: 0, value: "#3b82f6ff", easing: "linear" },
{ time: 1, value: "#f97316ff", easing: "linear" },
{ time: 2, value: "#3b82f6ff", easing: "linear" },
] },
{ target: "Box", property: "event", keys: [
{ time: 1, value: "bounce", easing: "step" },
] },
],
markers: [{ time: 0.5, name: "half" }],
});
class BindScene extends Scene {
async load(engine) {
await super.load(engine);
const boxNode = new WorldNode();
boxNode.setName("Box");
boxNode.setContentSize(Vector2.create(64, 64));
boxNode.setLocalPosition(Vector2.create(120, 180));
const paint = boxNode.addComponent(Paint);
paint.setColor(new Color(1, 1, 1, 1));
const root = this.getRoot();
root.addChild(boxNode);
timeline.bind(root);
timeline.setEventHandler((targetName, eventName) => {
console.log(targetName, eventName);
});
timeline.setMarkerHandler((markerName) => {
console.log(markerName);
});
timeline.play();
}
tick(timeDelta) {
super.tick(timeDelta);
timeline.tick(timeDelta);
}
}
const engineConfiguration = new EngineConfiguration();
engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
const engine = new Engine(engineConfiguration);
engine.run(new BindScene());Animator
Animator, AnimationState, AnimationTransition, and AnimationClip form a state machine that attaches a frame clip to each state, moves between states by parameter conditions, and blends two states. (the same structure as Unity's Animator state machine)
animator.addState(state)andaddTransition(transition)add to their lists and return the index.getStates()andgetTransitions()return the engine'sList. It starts in the first state added.AnimationStateholds a clip (setClip), a speed (setSpeed), and looping (setLoop,nullfollows the clip).AnimationTransitionconnects two states withsetFrom(stateIndex)andsetTo(stateIndex). WithsetFrom(null)it can be taken from any state (Any State). Add conditions withaddCondition(name, AnimationConditionMode, threshold); withsetExitTime(normalizedTime)it is taken only when that time is passed, and the two states blend forsetDuration(seconds).- Parameters are set with
setFloat,setInteger,setBool, andsetTrigger. A trigger used in a condition is reset when the transition is taken. animator.tick(timeDelta)advances the state time, checks Any State transitions first and then the rest in the order added, and takes the first one that matches. No new transition is checked while blending.- Read the chosen frame with
getCurrentFrame(), and while blending withgetNextFrame()andgetTransitionWeight(). AnimationClipholds a list of frame regions, a duration (seconds), and a loop flag.AnimationClip.fromAtlas(atlasJson, frameIds, framesPerSecond, isLoop)takes regions from an atlas table and sets the duration to the frame count divided by frames per second.
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 = AnimationClip.fromAtlas({ frames: { run0: { frame: { x: 0, y: 32, w: 32, h: 32 } }, run1: { frame: { x: 32, y: 32, w: 32, h: 32 } } } }, ["run0", "run1"], 4, 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.25);
const frame = animator.getCurrentFrame();
console.log(animator.getCurrentStateIndex(), animator.isInTransition(), frame.position.y);Animator only picks frame regions and does not draw, so the game puts the chosen region on a Sprite. For the simple case of only switching clips by character state, you can also combine FiniteStateMachine and SpriteAnimator, calling play in a state's enter.
import { Engine, EngineConfiguration, Scene, WorldNode, Sprite, SpriteAnimator, FiniteStateMachine, ImageAsset, Vector2, Rect } from "./build/vanilla.js";
class StateScene extends Scene {
#stateMachine;
constructor() {
super();
this.#stateMachine = new FiniteStateMachine();
}
async load(engine) {
await super.load(engine);
const imageAsset = new ImageAsset();
await imageAsset.load("examples/assets/spritesheet.png");
const image = imageAsset.getImage();
const node = new WorldNode();
node.setContentSize(Vector2.create(200, 200));
node.setLocalPosition(Vector2.create(640, 360));
node.addComponent(Sprite);
const spriteAnimator = node.addComponent(SpriteAnimator);
spriteAnimator.addClip("idle", image, [Rect.create(0, 0, 200, 200), Rect.create(200, 0, 200, 200)], 4, true);
spriteAnimator.addClip("run", image, [Rect.create(0, 200, 200, 200), Rect.create(200, 200, 200, 200), Rect.create(400, 200, 200, 200)], 10, true);
const root = this.getRoot();
root.addChild(node);
const stateMachine = this.#stateMachine;
stateMachine.addState("idle", {
enter: () => {
spriteAnimator.playClip("idle");
},
tick: (timeDelta, stateSeconds) => {
if (stateSeconds >= 2) {
stateMachine.changeState("run");
}
},
});
stateMachine.addState("run", {
enter: () => {
spriteAnimator.playClip("run");
},
tick: (timeDelta, stateSeconds) => {
if (stateSeconds >= 1) {
stateMachine.changeState("idle");
}
},
});
stateMachine.changeState("idle");
}
tick(timeDelta) {
super.tick(timeDelta);
this.#stateMachine.tick(timeDelta);
}
}
const engineConfiguration = new EngineConfiguration();
engineConfiguration.referenceResolutionSize = Vector2.create(1280, 720);
const engine = new Engine(engineConfiguration);
engine.run(new StateScene());Things to watch out for
Animation,Timeline, andFiniteStateMachinedo not advance time on their own. Calltick(timeDelta)from the scene'stick. Tweens handed over withscene.startTweenare updated by the scene.- The image for
setFramesFromRectsandaddClipmust be anHTMLImageElement. For anImageAsset, passgetImage()(setFramesFromRectsdoes nothing when given anything else). SpriteAnimatorlooks up theSpriteon the same node. Without aSprite, the image does not change.Timeline.seekdoes not fire events or markers. Events only fire whentickpasses their time.Timeline.loadFromUrlreads the response as JSON without checking its status. A wrong URL fails with a JSON parse error.
Related classes
Tween, TweenProperty, Frame, Animation, Sprite, SpriteAnimator, Timeline, ShaderSprite, ParticleSystem, ScreenEffect, Animator, AnimationState, AnimationTransition, AnimationClip, FiniteStateMachine, Scene