time-and-timers
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTime and Timers
时间与计时器
Clock plugin, TimerEvent, delays, loops, Timeline event sequencing, pausing time, time scale, and delta time in Phaser 4.
Key source paths: , , , ,
Related skills: ../scenes/SKILL.md, ../tweens/SKILL.md
src/time/Clock.jssrc/time/TimerEvent.jssrc/time/Timeline.jssrc/time/typedefs/src/time/events/Clock插件、TimerEvent、延迟、循环、Timeline事件序列、暂停时间、时间缩放以及Phaser 4中的delta time。
核心源码路径: , , , ,
相关技能: ../scenes/SKILL.md, ../tweens/SKILL.md
src/time/Clock.jssrc/time/TimerEvent.jssrc/time/Timeline.jssrc/time/typedefs/src/time/events/Quick Start
快速入门
js
// In a Scene's create() method:
// One-shot delayed call (fires once after 1 second)
this.time.delayedCall(1000, () => {
console.log('One second later');
});
// Repeating timer (fires 5 times, once every 500ms)
this.time.addEvent({
delay: 500,
callback: () => { console.log('tick'); },
repeat: 4 // 4 repeats = 5 total fires
});
// Infinite loop timer
this.time.addEvent({
delay: 1000,
callback: this.spawnEnemy,
callbackScope: this,
loop: true
});this.timeClock'Clock'timeTimerEventjs
// 在场景的create()方法中:
// 一次性延迟调用(1秒后触发一次)
this.time.delayedCall(1000, () => {
console.log('1秒后触发');
});
// 重复计时器(触发5次,每500ms一次)
this.time.addEvent({
delay: 500,
callback: () => { console.log('tick'); },
repeat: 4 // 4次重复 = 总共触发5次
});
// 无限循环计时器
this.time.addEvent({
delay: 1000,
callback: this.spawnEnemy,
callbackScope: this,
loop: true
});this.timeClocktime'Clock'TimerEventCore Concepts
核心概念
Clock (this.time)
Clock(this.time)
The Clock is a Scene-level plugin that tracks game time and updates all of its TimerEvents each frame. Key properties:
- -- current time in ms (equivalent to
nowpassed to the scenetimemethod).update - -- timestamp when the scene started.
startTime - -- multiplier applied to delta time. Default
timeScale. Values above 1 speed up all timers; below 1 slow them down;1freezes time.0 - -- when
paused, no TimerEvents are updated.true
The Clock listens to (to flush pending additions/removals) and (to tick active events). It is automatically shut down and destroyed with the scene.
PRE_UPDATEUPDATEClock是场景级插件,用于跟踪游戏时间并在每一帧更新所有TimerEvent对象。关键属性:
- -- 当前时间(毫秒),与传递给场景
now方法的update参数等效。time - -- 场景启动时的时间戳。
startTime - -- 应用于delta time的乘数,默认值为
timeScale。大于1的值会加速所有计时器;小于1的值会减慢计时器;1会冻结时间。0 - -- 当值为
paused时,所有TimerEvent都不会被更新。true
Clock会监听(用于处理待添加/移除的计时器)和(用于触发活跃事件)事件。它会随场景自动关闭和销毁。
PRE_UPDATEUPDATETimerEvent
TimerEvent
A TimerEvent accumulates elapsed time each frame: . When , the callback fires. After all repeats are exhausted the event is removed from the Clock on the next frame.
elapsed += delta * clock.timeScale * event.timeScaleelapsed >= delayKey properties set via config: , , , , , , , , .
delayrepeatloopcallbackcallbackScopeargstimeScalestartAtpausedTimerEvent会在每一帧累积经过的时间:。当时,回调函数会被触发。当所有重复次数耗尽后,事件会在下一帧从Clock中移除。
elapsed += delta * clock.timeScale * event.timeScaleelapsed >= delay通过配置项设置的关键属性:、、、、、、、、。
delayrepeatloopcallbackcallbackScopeargstimeScalestartAtpausedTimeline (this.add.timeline)
Timeline(this.add.timeline)
A Timeline is a sequencer for scheduling actions at specific points in time. Unlike the Clock (which manages independent timers), a Timeline runs a linear sequence of events keyed by absolute or relative timestamps.
js
const timeline = this.add.timeline([
{ at: 0, run: () => { /* immediate */ } },
{ at: 1000, run: () => { /* at 1s */ } },
{ at: 2500, tween: { targets: sprite, alpha: 0, duration: 500 } }
]);
timeline.play();Timelines always start paused. You must call to start them. They are created via the GameObjectFactory and destroyed automatically when the scene shuts down.
play()Timeline是用于在特定时间点调度动作的序列器。与Clock(管理独立计时器)不同,Timeline会按绝对或相对时间戳执行线性事件序列。
js
const timeline = this.add.timeline([
{ at: 0, run: () => { /* 立即执行 */ } },
{ at: 1000, run: () => { /* 1秒时执行 */ } },
{ at: 2500, tween: { targets: sprite, alpha: 0, duration: 500 } }
]);
timeline.play();Timeline创建后默认处于暂停状态,必须调用才能启动。它通过GameObjectFactory创建,并随场景关闭自动销毁。
play()Common Patterns
常见模式
Delayed Call
延迟调用
js
// Shorthand -- fires once, no repeat
this.time.delayedCall(2000, () => {
this.scene.start('GameOver');
});js
// 简写形式 -- 仅触发一次,无重复
this.time.delayedCall(2000, () => {
this.scene.start('GameOver');
});Repeating Timer with Finite Count
有限次数重复计时器
js
// repeat: 9 means 10 total fires (1 initial + 9 repeats)
const timer = this.time.addEvent({
delay: 200,
callback: this.fireBullet,
callbackScope: this,
repeat: 9
});
// Check progress
timer.getRepeatCount(); // repeats remaining
timer.getOverallProgress(); // 0..1 across all repeatsjs
// repeat: 9表示总共触发10次(1次初始触发 + 9次重复)
const timer = this.time.addEvent({
delay: 200,
callback: this.fireBullet,
callbackScope: this,
repeat: 9
});
// 检查进度
timer.getRepeatCount(); // 剩余重复次数
timer.getOverallProgress(); // 所有重复的整体进度(0到1)Infinite Loop
无限循环
js
const spawner = this.time.addEvent({
delay: 3000,
callback: this.spawnWave,
callbackScope: this,
loop: true
});
// Stop it later
spawner.remove(); // or spawner.paused = true to pauseSetting is equivalent to .
repeat: -1loop: truejs
const spawner = this.time.addEvent({
delay: 3000,
callback: this.spawnWave,
callbackScope: this,
loop: true
});
// 后续停止计时器
spawner.remove(); // 或者设置spawner.paused = true来暂停设置与效果相同。
repeat: -1loop: trueFirst-Fire Shortcut with startAt
使用startAt实现首次快速触发
js
// First fire happens quickly (after 100ms), then every 2s
this.time.addEvent({
delay: 2000,
callback: this.heartbeat,
callbackScope: this,
loop: true,
startAt: 1900 // pre-fill elapsed so first fire is at 100ms
});js
// 首次触发快速执行(100ms后),之后每2秒触发一次
this.time.addEvent({
delay: 2000,
callback: this.heartbeat,
callbackScope: this,
loop: true,
startAt: 1900 // 预填充已流逝时间,使首次触发在100ms后执行
});Stopping and Removing Timers
停止与移除计时器
js
const timer = this.time.addEvent({ delay: 1000, loop: true, callback: fn });
// Option 1: Remove from clock (schedules removal next frame)
timer.remove(); // silently expires
timer.remove(true); // fires callback one last time, then expires
// Option 2: Remove via Clock
this.time.removeEvent(timer);
// Option 3: Remove all timers
this.time.removeAllEvents();js
const timer = this.time.addEvent({ delay: 1000, loop: true, callback: fn });
// 方式1:从Clock中移除(安排在下一帧移除)
timer.remove(); // 静默过期
timer.remove(true); // 最后一次触发回调,然后过期
// 方式2:通过Clock移除
this.time.removeEvent(timer);
// 方式3:移除所有计时器
this.time.removeAllEvents();Pausing and Resuming
暂停与恢复
js
// Pause the entire Clock (all timers freeze)
this.time.paused = true;
this.time.paused = false;
// Pause a single timer
timer.paused = true;
timer.paused = false;js
// 暂停整个Clock(所有计时器冻结)
this.time.paused = true;
this.time.paused = false;
// 暂停单个计时器
timer.paused = true;
timer.paused = false;Time Scale (Slow Motion / Fast Forward)
时间缩放(慢动作/快进)
js
// Slow all timers in this scene to half speed
this.time.timeScale = 0.5;
// Speed up a single timer to 2x
timer.timeScale = 2;
// Combined: effective scale = clock.timeScale * event.timeScale
// So 0.5 * 2 = 1x for that specific timerjs
// 将当前场景中所有计时器速度减慢至一半
this.time.timeScale = 0.5;
// 将单个计时器速度加快至2倍
timer.timeScale = 2;
// 组合效果:实际缩放比例 = clock.timeScale * event.timeScale
// 因此0.5 * 2 = 该计时器的实际速度为1倍Reading Timer State
读取计时器状态
js
timer.getProgress(); // 0..1 for current iteration
timer.getOverallProgress(); // 0..1 across all repeats
timer.getElapsed(); // ms elapsed this iteration
timer.getElapsedSeconds(); // seconds elapsed this iteration
timer.getRemaining(); // ms until next fire
timer.getRemainingSeconds(); // seconds until next fire
timer.getOverallRemaining(); // ms until final fire
timer.getOverallRemainingSeconds(); // seconds until final fire
timer.getRepeatCount(); // repeats leftjs
timer.getProgress(); // 当前迭代的进度(0到1)
timer.getOverallProgress(); // 所有重复的整体进度(0到1)
timer.getElapsed(); // 当前迭代已流逝的毫秒数
timer.getElapsedSeconds(); // 当前迭代已流逝的秒数
timer.getRemaining(); // 距离下次触发的毫秒数
timer.getRemainingSeconds(); // 距离下次触发的秒数
timer.getOverallRemaining(); // 距离最终触发的毫秒数
timer.getOverallRemainingSeconds(); // 距离最终触发的秒数
timer.getRepeatCount(); // 剩余重复次数Timeline: Sequencing Events
Timeline:事件序列编排
js
const timeline = this.add.timeline([
{
at: 0,
run: () => { this.title.setAlpha(1); },
sound: 'intro'
},
{
at: 2000,
tween: { targets: this.title, y: 100, duration: 1000 },
sound: { key: 'whoosh', config: { volume: 0.5 } }
},
{
at: 4000,
set: { alpha: 0 },
target: this.title,
event: 'INTRO_DONE'
}
]);
timeline.on('INTRO_DONE', (target) => { /* custom event */ });
timeline.on('complete', (tl) => { /* all events ran */ });
timeline.play();js
const timeline = this.add.timeline([
{
at: 0,
run: () => { this.title.setAlpha(1); },
sound: 'intro'
},
{
at: 2000,
tween: { targets: this.title, y: 100, duration: 1000 },
sound: { key: 'whoosh', config: { volume: 0.5 } }
},
{
at: 4000,
set: { alpha: 0 },
target: this.title,
event: 'INTRO_DONE'
}
]);
timeline.on('INTRO_DONE', (target) => { /* 自定义事件处理 */ });
timeline.on('complete', (tl) => { /* 所有事件执行完成 */ });
timeline.play();Timeline: Relative Timing with from
and in
frominTimeline:使用from
和in
实现相对计时
frominjs
const timeline = this.add.timeline([
{ at: 1000, run: stepOne }, // absolute: 1s from start
{ from: 500, run: stepTwo }, // relative: 500ms after previous (1.5s)
{ from: 1000, run: stepThree } // relative: 1000ms after previous (2.5s)
]);- -- absolute ms from timeline start (default 0).
at - -- offset from current
intime (useful when adding events to a running timeline).elapsed - -- offset from the previous event's start time.
from
Priority: overrides , which overrides .
frominatjs
const timeline = this.add.timeline([
{ at: 1000, run: stepOne }, // 绝对时间:从开始后1秒
{ from: 500, run: stepTwo }, // 相对时间:上一个事件后500ms(1.5秒时)
{ from: 1000, run: stepThree } // 相对时间:上一个事件后1000ms(2.5秒时)
]);- -- 相对于Timeline启动的绝对毫秒数(默认0)。
at - -- 相对于当前
in时间的偏移量(在运行中的Timeline添加事件时有用)。elapsed - -- 相对于上一个事件启动时间的偏移量。
from
优先级:覆盖,覆盖。
fromininatTimeline: Conditional Events
Timeline:条件事件
js
const timeline = this.add.timeline([
{
at: 5000,
if: () => this.player.health > 0,
run: () => { this.showBonusRound(); }
}
]);If the callback returns , the event is skipped (marked complete but actions are not executed).
iffalsejs
const timeline = this.add.timeline([
{
at: 5000,
if: () => this.player.health > 0,
run: () => { this.showBonusRound(); }
}
]);如果回调返回,该事件会被跳过(标记为完成但不执行动作)。
iffalseTimeline: Looping
Timeline:循环
js
const timeline = this.add.timeline([
{ at: 0, run: () => console.log('start') },
{ at: 1000, run: () => console.log('end') }
]);
timeline.repeat().play(); // infinite loop
timeline.repeat(3).play(); // loop 3 additional times (4 total runs)
timeline.repeat(false).play(); // no loopingThe callback on a TimelineEventConfig fires on repeat iterations (not the first run).
loopjs
const timeline = this.add.timeline([
{ at: 0, run: () => console.log('开始') },
{ at: 1000, run: () => console.log('结束') }
]);
timeline.repeat().play(); // 无限循环
timeline.repeat(3).play(); // 额外循环3次(总共执行4次)
timeline.repeat(false).play(); // 不循环TimelineEventConfig中的回调会在重复迭代时触发(首次运行时不会触发)。
loopTimeline: Pause, Resume, Stop, Reset
Timeline:暂停、恢复、停止、重置
js
timeline.pause(); // freezes elapsed counter and pauses spawned tweens
timeline.resume(); // resumes elapsed counter and unpauses spawned tweens
timeline.stop(); // sets paused=true, complete=true
timeline.reset(); // elapsed=0, all events marked incomplete, starts playing
timeline.isPlaying(); // true if not paused and not complete
timeline.getProgress(); // 0..1 based on events completed / total eventsjs
timeline.pause(); // 冻结已流逝时间计数器并暂停生成的补间
timeline.resume(); // 恢复已流逝时间计数器并恢复生成的补间
timeline.stop(); // 设置paused=true,complete=true
timeline.reset(); // elapsed=0,所有事件标记为未完成,开始播放
timeline.isPlaying(); // 如果未暂停且未完成则返回true
timeline.getProgress(); // 根据已完成事件数/总事件数返回0到1的进度值Timeline: Time Scale
Timeline:时间缩放
js
timeline.timeScale = 2; // double speed
timeline.timeScale = 0.5; // half speedNote: Timeline does not affect tweens created by the timeline. Set tween timeScale separately.
timeScalejs
timeline.timeScale = 2; // 速度加倍
timeline.timeScale = 0.5; // 速度减半注意:Timeline的不会影响其创建的补间。需单独设置补间的timeScale,或使用TweenManager。
timeScaleTimeline: Full Cutscene Example
Timeline:完整过场动画示例
Timelines excel at choreographing cutscenes with mixed actions (callbacks, tweens, sounds, property sets, and custom events):
js
class CutsceneScene extends Phaser.Scene {
create() {
const timeline = this.add.timeline([
{
at: 0,
run: () => { console.log('Start!'); }
},
{
at: 1000,
tween: {
targets: this.player,
x: 400,
duration: 500,
ease: 'Power2'
}
},
{
at: 1500,
sound: 'doorOpen'
},
{
at: 2000,
set: { visible: true },
target: this.door
},
{
from: 500,
run: () => { console.log('Relative timing'); }
},
{
at: 5000,
event: 'cutsceneDone',
stop: true
}
]);
timeline.on('cutsceneDone', () => {
this.scene.start('GameScene');
});
timeline.play();
}
}Timeline擅长编排包含多种动作(回调、补间、音效、属性设置和自定义事件)的过场动画:
js
class CutsceneScene extends Phaser.Scene {
create() {
const timeline = this.add.timeline([
{
at: 0,
run: () => { console.log('开始!'); }
},
{
at: 1000,
tween: {
targets: this.player,
x: 400,
duration: 500,
ease: 'Power2'
}
},
{
at: 1500,
sound: 'doorOpen'
},
{
at: 2000,
set: { visible: true },
target: this.door
},
{
from: 500,
run: () => { console.log('相对计时'); }
},
{
at: 5000,
event: 'cutsceneDone',
stop: true
}
]);
timeline.on('cutsceneDone', () => {
this.scene.start('GameScene');
});
timeline.play();
}
}Timer Reset and Reuse
计时器重置与复用
A completed can be reset with a new config and re-added to the Clock:
TimerEventjs
const timer = this.time.addEvent({
delay: 1000,
callback: this.phase1,
callbackScope: this,
repeat: 2
});
// Later, after it completes, reconfigure and re-add:
timer.reset({
delay: 500,
callback: this.phase2,
callbackScope: this,
repeat: 4
});
this.time.addEvent(timer); // must re-add; reset() alone does not schedule it已完成的可以通过新配置重置并重新添加到Clock:
TimerEventjs
const timer = this.time.addEvent({
delay: 1000,
callback: this.phase1,
callbackScope: this,
repeat: 2
});
// 后续,完成后重新配置并添加:
timer.reset({
delay: 500,
callback: this.phase2,
callbackScope: this,
repeat: 4
});
this.time.addEvent(timer); // 必须重新添加;仅调用reset()不会调度计时器Configuration Reference
配置参考
TimerEventConfig
TimerEventConfig
| Property | Type | Default | Description |
|---|---|---|---|
| number | | Delay in ms before the callback fires |
| number | | Times to repeat after first fire. Use |
| boolean | | If |
| function | -- | Function called when the timer fires |
| any | TimerEvent | The |
| Array | | Extra arguments passed to the callback |
| number | | Per-event time multiplier |
| number | | Pre-fill elapsed time in ms (makes first fire happen sooner) |
| boolean | | Start the timer in a paused state |
| 属性 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| number | | 回调触发前的延迟时间(毫秒) |
| number | | 首次触发后的重复次数,使用 |
| boolean | | 如果为 |
| function | -- | 计时器触发时调用的函数 |
| any | TimerEvent | 回调函数的 |
| Array | | 传递给回调函数的额外参数 |
| number | | 单个计时器的时间乘数 |
| number | | 预填充的已流逝时间(毫秒),使首次触发更快发生 |
| boolean | | 计时器以暂停状态启动 |
TimelineEventConfig
TimelineEventConfig
| Property | Type | Default | Description |
|---|---|---|---|
| number | | Absolute time in ms from timeline start |
| number | -- | Offset from current elapsed (overrides |
| number | -- | Offset from previous event time (overrides |
| function | -- | Callback invoked when event fires |
| function | -- | Callback invoked on repeat iterations (not first run) |
| function | -- | Guard function; return |
| string | -- | Event name emitted on the Timeline instance |
| any | -- | Scope for |
| object | -- | Key-value pairs applied to |
| TweenConfig | -- | Tween config or instance created when event fires |
| string/object | -- | Sound key or |
| boolean | | Remove this event after it fires |
| boolean | | Stop the entire timeline when this event fires |
| 属性 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| number | | 相对于Timeline启动的绝对时间(毫秒) |
| number | -- | 相对于当前已流逝时间的偏移量(覆盖 |
| number | -- | 相对于上一个事件时间的偏移量(覆盖 |
| function | -- | 事件触发时调用的回调 |
| function | -- | 重复迭代时调用的回调(首次运行时不触发) |
| function | -- | 守卫函数;返回 |
| string | -- | 在Timeline实例上触发的事件名称 |
| any | -- | |
| object | -- | 事件触发时应用于 |
| TweenConfig | -- | 事件触发时创建的补间配置或实例 |
| string/object | -- | 要播放的音效键或 |
| boolean | | 事件触发后移除该事件 |
| boolean | | 该事件触发时停止整个Timeline |
TimelineEvent (Internal)
TimelineEvent(内部)
The processed event object stored in . Extends config with:
timeline.events[]| Property | Type | Description |
|---|---|---|
| boolean | Whether this event has fired |
| number | Resolved absolute time in ms |
| number | How many times this event has repeated |
| Tween/TweenChain | Reference to spawned tween (if any) |
存储在中的处理后事件对象,在配置基础上扩展了以下属性:
timeline.events[]| 属性 | 类型 | 描述 |
|---|---|---|
| boolean | 该事件是否已触发 |
| number | 解析后的绝对时间(毫秒) |
| number | 该事件已重复的次数 |
| Tween/TweenChain | 生成的补间引用(如有) |
Events
事件
Timeline Events
Timeline事件
| Event | Constant | Listener Signature | Fired When |
|---|---|---|---|
| | | All timeline events have been run |
Custom events via the property in TimelineEventConfig are also emitted on the Timeline instance with signature .
event(target)| 事件 | 常量 | 监听器签名 | 触发时机 |
|---|---|---|---|
| | | 所有Timeline事件执行完成时 |
通过TimelineEventConfig中属性定义的自定义事件也会在Timeline实例上触发,签名为。
event(target)TimerEvent / Clock
TimerEvent / Clock
TimerEvent and Clock do not emit EventEmitter events. Timers use the property directly. The Clock is managed by scene lifecycle events (, , , ).
callbackPRE_UPDATEUPDATESHUTDOWNDESTROYTimerEvent和Clock不会触发EventEmitter事件。计时器直接使用属性。Clock由场景生命周期事件(、、、)管理。
callbackPRE_UPDATEUPDATESHUTDOWNDESTROYAPI Quick Reference
API速查
Clock (this.time)
Clock(this.time)
| Method | Signature | Returns | Description |
|---|---|---|---|
| | | Create and schedule a timer event |
| | | Shorthand for a one-shot delayed call |
| | | Remove specific timer(s) |
| | | Schedule removal of all active timers |
| | | Clear timers not yet added to active list |
| Property | Type | Description |
|---|---|---|
| number | Current clock time in ms |
| number | Time the scene started |
| number | Delta multiplier for all timers |
| boolean | Freeze all timers |
| 方法 | 签名 | 返回值 | 描述 |
|---|---|---|---|
| | | 创建并调度一个计时器事件 |
| | | 一次性延迟调用的简写形式 |
| | | 移除指定的一个或多个计时器 |
| | | 安排移除所有活跃计时器 |
| | | 清除尚未添加到活跃列表的计时器 |
| 属性 | 类型 | 描述 |
|---|---|---|
| number | 当前Clock时间(毫秒) |
| number | 场景启动时间 |
| number | 所有计时器的delta时间乘数 |
| boolean | 冻结所有计时器 |
TimerEvent
TimerEvent
| Method | Returns | Description |
|---|---|---|
| number | 0..1 progress of current iteration |
| number | 0..1 progress across all repeats |
| number | Elapsed ms this iteration |
| number | Elapsed seconds this iteration |
| number | Ms until next fire |
| number | Seconds until next fire |
| number | Ms until final fire |
| number | Seconds until final fire |
| number | Repeats remaining |
| void | Expire the timer (optionally fire callback) |
| TimerEvent | Reinitialize with new config |
| void | Null out callback references |
| 方法 | 返回值 | 描述 |
|---|---|---|
| number | 当前迭代的进度(0到1) |
| number | 所有重复的整体进度(0到1) |
| number | 当前迭代已流逝的毫秒数 |
| number | 当前迭代已流逝的秒数 |
| number | 距离下次触发的毫秒数 |
| number | 距离下次触发的秒数 |
| number | 距离最终触发的毫秒数 |
| number | 距离最终触发的秒数 |
| number | 剩余重复次数 |
| void | 使计时器过期(可选触发回调) |
| TimerEvent | 使用新配置重新初始化计时器 |
| void | 清空回调引用 |
Timeline (this.add.timeline)
Timeline(this.add.timeline)
| Method | Signature | Returns | Description |
|---|---|---|---|
| | | Append events to the timeline |
| | | Start playing (default resets to start) |
| | | Pause timeline and spawned tweens |
| | | Resume timeline and spawned tweens |
| | | Stop (sets paused + complete) |
| | | Reset elapsed and all events to incomplete |
| | | Set loop count (-1/true=infinite, false=none) |
| | | Remove all events, reset elapsed, pause |
| | boolean | True if not paused and not complete |
| | number | 0..1 based on completed event count |
| Property | Type | Description |
|---|---|---|
| number | Current elapsed time in ms |
| number | Delta multiplier (does not affect spawned tweens) |
| boolean | Whether timeline is paused |
| boolean | Whether all events have run |
| number | Number of additional loops (0=none, -1=infinite) |
| number | Current loop iteration |
| number | Count of events that have fired |
| TimelineEvent[] | The internal event array |
| 方法 | 签名 | 返回值 | 描述 |
|---|---|---|---|
| | | 向Timeline追加事件 |
| | | 开始播放(默认重置到起始位置) |
| | | 暂停Timeline和生成的补间 |
| | | 恢复Timeline和生成的补间 |
| | | 停止播放(设置paused和complete为true) |
| | | 重置已流逝时间并将所有事件标记为未完成 |
| | | 设置循环次数(-1/true表示无限,false表示无循环) |
| | | 移除所有事件,重置已流逝时间并暂停 |
| | boolean | 如果未暂停且未完成则返回true |
| | number | 根据已完成事件数/总事件数返回0到1的进度值 |
| 属性 | 类型 | 描述 |
|---|---|---|
| number | 当前已流逝时间(毫秒) |
| number | delta时间乘数(不影响生成的补间) |
| boolean | Timeline是否处于暂停状态 |
| boolean | 所有事件是否已执行完成 |
| number | 额外循环次数(0表示无循环,-1表示无限) |
| number | 当前循环迭代次数 |
| number | 已触发的事件数量 |
| TimelineEvent[] | 内部事件数组 |
Gotchas
注意事项
- repeat vs total fires. means 5 total callback invocations (1 initial + 4 repeats). This is a common off-by-one source.
repeat: 4 - Zero delay with repeat throws. A with
TimerEventand any repeat/loop will throwdelay: 0.'TimerEvent infinite loop created via zero delay' - Timelines start paused. You must call after creation. Forgetting this is a frequent mistake.
timeline.play() - Timeline timeScale does not affect tweens. Setting only scales the timeline's own elapsed counter. Tweens created by the timeline run at their own speed. Set tween
timeline.timeScaleseparately or use the TweenManager.timeScale - once events are removed permanently. Timeline events with are spliced out after firing and will not reappear on
once: trueor when looping.reset() - Timer additions are deferred. pushes to a pending list processed in
addEvent(). The timer will not be active until the next frame.preUpdate - Clock paused vs timeScale 0. Both freeze timers, but skips the update loop entirely, while
paused = truestill runs the loop with zero delta. PrefertimeScale = 0for a full freeze.paused - callbackScope default. If you omit , the TimerEvent itself becomes
callbackScopeinside the callback, not the scene. Use arrow functions or passthisexplicitly.callbackScope: this - Reusing TimerEvent instances. You can pass a object to
TimerEvent, but it must not be in a completed state. The Clock will reset its elapsed and dispatch state.addEvent() - Timeline chains. Each
fromoffset is relative to the previous event's resolved time, not the previousfromvalue. Events are processed in array order.from - Scene pause pauses the Timeline. When a scene is paused (), the Timeline's update loop stops too, since Timeline updates are driven by the scene's update step.
scene.pause() - does not re-add to Clock. Calling
timer.reset()reinitializes the timer but does not schedule it. You must calltimer.reset(config)again after resetting.this.time.addEvent(timer)
- 重复次数与总触发次数:表示总共触发5次回调(1次初始触发 + 4次重复)。这是常见的差一错误来源。
repeat: 4 - 零延迟加重复会抛出错误:且设置了重复/循环的
delay: 0会抛出TimerEvent错误。'TimerEvent infinite loop created via zero delay' - Timeline默认暂停:创建后必须调用才能启动。忘记这一点是常见错误。
timeline.play() - Timeline时间缩放不影响补间:设置仅缩放Timeline自身的已流逝计数器。Timeline创建的补间会以自身速度运行,需单独设置补间的
timeline.timeScale或使用TweenManager。timeScale - once事件会被永久移除:设置的Timeline事件触发后会被移除,调用
once: true或循环时不会重新出现。reset() - 计时器添加是延迟处理的:会将计时器加入待处理列表,在
addEvent()中处理。计时器要到下一帧才会激活。preUpdate - Clock暂停与timeScale为0的区别:两者都会冻结计时器,但会完全跳过更新循环,而
paused = true仍会运行循环但delta为0。完全冻结时优先使用timeScale = 0。paused - callbackScope默认值:如果省略,回调函数中的
callbackScope会是TimerEvent实例而非场景。请使用箭头函数或显式传递this。callbackScope: this - 复用TimerEvent实例:可以将对象传递给
TimerEvent,但该对象不能处于已完成状态。Clock会重置其已流逝时间和调度状态。addEvent() - Timeline的链式结构:每个
from偏移量是相对于上一个事件的解析时间,而非上一个from值。事件按数组顺序处理。from - 场景暂停会暂停Timeline:当场景暂停()时,Timeline的更新循环也会停止,因为Timeline的更新由场景的update步骤驱动。
scene.pause() - 不会重新添加到Clock:调用
timer.reset()会重新初始化计时器,但不会调度它。重置后必须再次调用timer.reset(config)。this.time.addEvent(timer)
Source File Map
源码文件映射
| File | Description |
|---|---|
| Scene Clock plugin -- creates, updates, removes TimerEvents |
| Individual timer -- delay, repeat, loop, progress tracking |
| Event sequencer -- scheduled actions, tweens, sounds, looping |
| Config typedef for |
| Config typedef for |
| Internal event object typedef |
| |
| Events namespace barrel file |
| 文件 | 描述 |
|---|---|
| 场景Clock插件 -- 创建、更新、移除TimerEvent |
| 单个计时器 -- 延迟、重复、循环、进度跟踪 |
| 事件序列器 -- 调度动作、补间、音效、循环 |
| |
| |
| 内部事件对象的类型定义 |
| Timeline的 |
| 事件命名空间的入口文件 |