360 Secure SkillHub
360 安全技能中心

tweens

该 Skill 是一份 Phaser 4 Tweens 参考文档,系统说明 this.tweens.add、属性值、缓动、yoyo、repeat/loop、stagger、Tween Chains、addCounter、回调、事件与 TweenManager 控制,并给出代码示例和 v3 迁移注意事项。它仅提供文字说明和示例,不包含可执行代码或项目脚手架。

分类:开发
phaserjs
热度 0.00
最近更新 2026-12-03 17:40:41

安装

发给 Agent
帮我安装这个技能:npx secure-skills-cli add phaserjs/phaser/tweens
兼容性
通用兼容
联网要求
不联网
数据出网
数据不出本机
Metadata
name
tweens
description
Phaser 4 tweens: this.tweens.add and this.add.tween, property values (relative, random, arrays, from/to, per-property config), easing names and easeParams, yoyo, hold, repeat and loop, stagger, Tween Chains (this.tweens.chain), number tweens (addCounter), callbacks and TWEEN events, persist, timeScale and the TweenManager. Use when moving, fading, scaling, pulsing, bobbing, shaking or bouncing an object, animating UI or a menu, counting a score up, or playing animations one after another. Corrects v3 habits: this.tweens.timeline() and createTimeline() are gone (use a chain, or this.add.timeline for mixed events); TweenChain.remove now removes the whole chain (removeTween removes one tween); tweens run on their own clock, so this.time.timeScale doesn't slow them. Triggers on: tween, tweens.add, ease, easing, yoyo, repeat, stagger, tween chain, addCounter, fade in, fade out, pulse, animate property.
metadata
{"phaser-version":"4.3.0"}

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.
  • targets is 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 set interpolation: 'linear', 'bezier' or 'catmull' (or a function), which passes through all of them.
  • scale tweens scaleX and scaleY, unless the target has an own scale property, as a plain object might.
  • A property config object can also hold getStart, getEnd and getActive callbacks, 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, .easeOut or .easeInOut. A bare name, such as 'Bounce', is the Out version.
  • Power0 is Linear. Power1 to Power4 are Quad, Cubic, Quart and Quint .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 against src/math/easing/EaseMap.js.
  • easeParams are passed after the progress: Elastic takes [ amplitude, period ] (default 0.1, 0.1), Back takes [ overshoot ] (1.70158), Stepped takes [ steps ].
  • A function works too: ease: (v) => v * v, where v goes from 0 to 1. The built-ins are in Phaser.Math.Easing, such as Phaser.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 as this.tweens.chain(config).
  • Chain-level keys: targets, tweens, delay, loop (alias repeat), loopDelay (alias repeatDelay), completeDelay, paused, persist, callbackScope and the tween-level callbacks. yoyo, hold and ease go on each tween.
  • chain.add([ configs ]) appends tweens, but they don't inherit the chain's targets: give each one targets, 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, onYoyo and onRepeat run 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).
  • onStart fires after the delay. onComplete never 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(), or this.tweens.paused.
  • this.tweens.timeScale (or setGlobalTimeScale(v)) scales every tween in the Scene. A tween's speed is tween.timeScale * this.tweens.timeScale.
  • create(config) makes a tween without starting it. Add it later with existing(tween).

TypeScript (4.3)

  • ease is string | Phaser.Types.Tweens.EaseFunction, delay accepts Phaser.Types.Tweens.GetDelayCallback, and interpolation accepts Phaser.Types.Tweens.InterpolationFunction, so function arguments are typed.
  • this.tweens.stagger() returns a GetDelayCallback.
  • loop, loopDelay and completeDelay accept number[] and Phaser.Types.Tweens.TweenRandomValue ({ randInt } or { randFloat }).

Gotchas

  • Tweens have their own clock. The TweenManager measures time with Date.now(), not the Scene Clock, so this.time.timeScale and this.time.paused don't affect tweens. Use this.tweens.timeScale and this.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() or restart() on it does nothing useful. Use persist: true, or make a new tween.
  • Dispose of a persisted tween with remove() then destroy(). destroy() alone leaves it in the TweenManager's list until the Scene shuts down.
  • repeat vs loop. repeat replays each property, straight after it ends. loop replays the whole tween once every property has ended.
  • A destroyed target ends its tween. A tween stops updating a target whose isDestroyed is true, so destroying a sprite mid-tween is safe.
  • All tweens in a Scene are destroyed when it shuts down, persisted or not.