Tweens
Changing properties over time with the Scene's TweenManager (this.tweens): tween config, values, easing, chains, counters, callbacks and control.
Source: src/tweens/TweenManager.js, src/tweens/tween/ (Tween, TweenChain, BaseTween, TweenData), src/tweens/builders/ (how a config is read), src/tweens/typedefs/, src/math/easing/EaseMap.js. Related: time-and-timers (Timeline), curves-and-paths (PathFollower), animations.
Quick start
const logo = this.add.image(100, this.scale.height / 2, 'logo');
this.tweens.add({
targets: logo,
x: this.scale.width - 100,
duration: 2000, // ms, default 1000
ease: 'Sine.easeInOut', // default 'Power0' (linear)
yoyo: true,
repeat: -1, // -1 = forever
onComplete: () => console.log('never, as it repeats forever')
});
this.tweens.add(config)creates the tween, adds it and starts it.this.add.tween(config)is the same.targetsis one object, an array, or a function returning them. Any object with numeric properties works, not only Game Objects.- A tween destroys itself when it finishes. Keep a reference only to control it while it runs, or set
persist: true(see Control).
Property values
Any key that isn't a config option is a property to tween. Put them in props: { ... } if a name clashes with a config key.
const sprite = this.add.sprite(200, 300, 'player');
this.tweens.add({
targets: sprite,
x: 600, // absolute
y: '-=100', // relative: '+=', '-=', '*=', '/='
angle: 'random(-45, 45)', // random float, picked when the tween starts
scale: { from: 0, to: 1 }, // start value set when the tween starts
alpha: { start: 0, to: 1 }, // start value set at once, even during a delay
delay: 500,
duration: 1000
});
this.tweens.add({
targets: sprite,
x: 'int(100, 900)', // random integer, inclusive
y: { value: 500, duration: 300, ease: 'Quad.easeIn', delay: 200 }, // per-property config
duration: 1000
});
- A function is called once per target and returns the end value:
x: (target, key, value, targetIndex, totalTargets, tween) => value + targetIndex * 50. - An array, such as
x: [ 100, 400, 200 ], tweens from the first value to the last and skips the middle ones, unless you setinterpolation: 'linear','bezier'or'catmull'(or a function), which passes through all of them. scaletweensscaleXandscaleY, unless the target has an ownscaleproperty, as a plain object might.- A property config object can also hold
getStart,getEndandgetActivecallbacks, with the same arguments as a function value. - Properties whose name starts with
_are never tweened.
Timing
| Key | Default | Meaning |
|---|---|---|
duration |
1000 |
ms for one play of each property. 0 or less becomes 0.01. |
delay |
0 |
ms before each property starts. A number, or a function (GetDelayCallback), such as this.tweens.stagger(...). |
hold |
0 |
ms to wait at the end value before a yoyo. |
yoyo |
false |
Play back to the start value. |
repeat |
0 |
Extra plays of each property. repeat: 1 plays twice. -1 is forever. |
repeatDelay |
0 |
ms before each repeat. |
flipX / flipY |
false |
Toggle the target's flip on each yoyo or repeat. |
loop |
0 |
Extra plays of the whole tween, after every property has finished. -1 is forever. |
loopDelay |
0 |
ms before each loop. |
completeDelay |
0 |
ms between finishing and onComplete. |
paused |
false |
Create paused. Call tween.play() or resume() to start. |
persist |
false |
Don't destroy the tween when it finishes. |
loop, loopDelay and completeDelay also take an array of numbers (one is picked at random), { randInt: [ min, max ] }, { randFloat: [ min, max ] }, or a function. They are picked once, when the tween is created.
repeat and the per-property keys can be set inside a property config, so properties can have different durations, delays and repeats.
Easing
- Names:
Linear,Quad,Cubic,Quart,Quint,Sine,Expo,Circ,Elastic,Back,Bounce,Stepped, each with.easeIn,.easeOutor.easeInOut. A bare name, such as'Bounce', is the Out version. Power0is Linear.Power1toPower4areQuad,Cubic,QuartandQuint.easeOut.- The short forms
'quad.in','sine.out'and'cubic.inout'work, in any case after the dot. - A name it doesn't recognise, such as
'easeInOutSine','Quadratic.Out'or'Sine.easeinout', silently becomes Linear. Check the spelling againstsrc/math/easing/EaseMap.js. easeParamsare passed after the progress:Elastictakes[ amplitude, period ](default 0.1, 0.1),Backtakes[ overshoot ](1.70158),Steppedtakes[ steps ].- A function works too:
ease: (v) => v * v, wherevgoes from 0 to 1. The built-ins are inPhaser.Math.Easing, such asPhaser.Math.Easing.Sine.InOut.
Stagger
this.tweens.stagger(value, config) returns a function to use as delay, or as a property value, for a tween with many targets.
const cards = [ 0, 1, 2, 3, 4 ].map((i) => this.add.image(200 + i * 150, 300, 'card'));
this.tweens.add({
targets: cards,
y: '+=40',
delay: this.tweens.stagger(100) // 0, 100, 200, ...
});
this.tweens.stagger(100, { from: 'center' }) // 5 targets: 200, 100, 0, 100, 200
this.tweens.stagger([ 0, 1000 ]) // spread 0 to 1000 across all targets
this.tweens.stagger(50, { grid: [ 10, 6 ], from: 'center', ease: 'cubic.out' })
StaggerConfig: start (offset added to each value), from ('first', 'center', 'last' or an index, default 0), ease, grid ([ width, height ]). It has no effect with one target.
Tween Chains
A chain plays tweens one after another.
const player = this.add.sprite(100, 400, 'player');
const shadow = this.add.image(100, 440, 'shadow');
const chain = this.tweens.chain({
targets: player, // each tween uses these unless it has its own
tweens: [
{ x: 600, duration: 800, ease: 'Power2' },
{ y: 200, duration: 500, ease: 'Bounce' },
{ targets: shadow, alpha: 0, duration: 300 }
],
delay: 500, // before the chain starts
loop: 1, // or `repeat`. -1 = forever
loopDelay: 300,
onComplete: () => this.scene.start('Next')
});
this.add.tweenchain(config)is the same asthis.tweens.chain(config).- Chain-level keys:
targets,tweens,delay,loop(aliasrepeat),loopDelay(aliasrepeatDelay),completeDelay,paused,persist,callbackScopeand the tween-level callbacks.yoyo,holdandeasego on each tween. chain.add([ configs ])appends tweens, but they don't inherit the chain'stargets: give each onetargets, or it throws.chain.removeTween(tween)removes one tween from the chain. Since 4.3,chain.remove()removes the whole chain from the TweenManager, as it does for a Tween.- Chain callbacks receive only
(chain, ...params).
Number tweens
A tween with no target, for a value you read yourself, such as a score counting up.
const scoreText = this.add.text(16, 16, '0');
this.tweens.addCounter({
from: 0,
to: 1500,
duration: 1000,
ease: 'Cubic.easeOut',
onUpdate: (tween) => scoreText.setText(Math.round(tween.getValue()))
});
It takes the usual timing and callback keys. The target is an object { value }.
Callbacks and events
Callbacks go in the config, or are set later with tween.setCallback('onComplete', fn, params). this is callbackScope, which defaults to the tween. Extra arguments go in on<Name>Params, such as onCompleteParams: [ 10 ].
| Callback | Event constant (string) | Arguments |
|---|---|---|
onActive |
TWEEN_ACTIVE ('active') |
(tween, targets) |
onStart |
TWEEN_START ('start') |
(tween, targets) |
onLoop |
TWEEN_LOOP ('loop') |
(tween, targets) |
onComplete |
TWEEN_COMPLETE ('complete') |
(tween, targets) |
onStop, onPause, onResume |
TWEEN_STOP, TWEEN_PAUSE, TWEEN_RESUME |
(tween, targets) |
onUpdate |
TWEEN_UPDATE ('update') |
callback (tween, target, key, current, previous) |
onYoyo, onRepeat |
TWEEN_YOYO, TWEEN_REPEAT |
callback (tween, target, key, current, previous) |
onUpdate,onYoyoandonRepeatrun once per property per target. Their events are emitted with the arguments in a different order:(tween, key, target, current, previous).- The constants are in
Phaser.Tweens.Events:tween.on(Phaser.Tweens.Events.TWEEN_COMPLETE, fn). onStartfires after the delay.onCompletenever fires for a tween that repeats or loops forever.
Control
const door = this.add.image(500, 400, 'door');
const tween = this.tweens.add({ targets: door, y: '-=200', duration: 800, paused: true, persist: true });
tween.play(); // start a paused tween; replays a persisted tween that has finished
tween.pause(); tween.resume();
tween.restart();
tween.seek(400); // ms from the start, including delays and repeats. Silent unless seek(ms, 16.6, true)
tween.setTimeScale(0.5); // this tween only
tween.updateTo('y', 50, true); // new end value while playing; true also moves the start to the current value
tween.complete(); // finish now and fire onComplete
tween.completeAfterLoop();// finish at the end of the current loop
tween.stop(); // finish now, fire onStop, not onComplete
// When you're done with a persisted tween:
tween.remove();
tween.destroy();
Read tween.progress (0 to 1, this play), totalProgress, elapsed, isPlaying(), isPaused(), hasTarget(obj).
TweenManager (this.tweens):
killTweensOf(target),getTweensOf(target),isTweening(target)(false when the tween is paused),killAll(),getTweens().pauseAll()/resumeAll(), orthis.tweens.paused.this.tweens.timeScale(orsetGlobalTimeScale(v)) scales every tween in the Scene. A tween's speed istween.timeScale * this.tweens.timeScale.create(config)makes a tween without starting it. Add it later withexisting(tween).
TypeScript (4.3)
easeisstring | Phaser.Types.Tweens.EaseFunction,delayacceptsPhaser.Types.Tweens.GetDelayCallback, andinterpolationacceptsPhaser.Types.Tweens.InterpolationFunction, so function arguments are typed.this.tweens.stagger()returns aGetDelayCallback.loop,loopDelayandcompleteDelayacceptnumber[]andPhaser.Types.Tweens.TweenRandomValue({ randInt }or{ randFloat }).
Gotchas
- Tweens have their own clock. The TweenManager measures time with
Date.now(), not the Scene Clock, sothis.time.timeScaleandthis.time.pauseddon't affect tweens. Usethis.tweens.timeScaleandthis.tweens.pauseAll(). Tweens stop while the Scene is paused or asleep. - Two tweens on the same property fight. Call
this.tweens.killTweensOf(target)before starting a new one, such as on hover in and out. - A finished tween is destroyed. Calling
play()orrestart()on it does nothing useful. Usepersist: true, or make a new tween. - Dispose of a persisted tween with
remove()thendestroy().destroy()alone leaves it in the TweenManager's list until the Scene shuts down. repeatvsloop.repeatreplays each property, straight after it ends.loopreplays the whole tween once every property has ended.- A destroyed target ends its tween. A tween stops updating a target whose
isDestroyedis true, so destroying a sprite mid-tween is safe. - All tweens in a Scene are destroyed when it shuts down, persisted or not.
