Phaser 3中Tween的useFrames参数引用位置及原理咨询
useFrames Tween Parameter: Consistent Animation Across Devices When working with Phaser 3's Tween system, it's common to notice animation inconsistencies across different devices—this happens because default tweens rely on real-time delta values, which fluctuate with device performance. The useFrames parameter fixes this by tying your tween's progression to game frames instead of real time.
How useFrames Works in Practice
Let's break down your example to see the difference:
var tween = this.tweens.add({ targets: textObj, alpha: 1.0, x: 300, delay: 0, yoyo: true, repeat: -1, duration: 1000, useFrames: true }); var frameNumber = 0; function update(time, delta) { frameNumber++; if (frameNumber == 250) { console.log(textObj.x); } }
- With
useFrames: true, every device will log254.20000000000002at frame 250. - If you set
useFrames: false, the logged value will vary—devices with higher performance will have advanced further in the tween, while slower devices will lag behind.
Diving Into the Source Code
You already found the key snippet in the Tween.update method, so let's unpack what it does:
update: function (timestamp, delta) { if (this.state === TWEEN_CONST.PAUSED) { return false; } if (this.useFrames) { delta = 1 * this.parent.timeScale; } delta *= this.timeScale; // ... rest of the update logic }
Here's the core insight:
- Normally,
deltais the time (in milliseconds) since the last frame (e.g., ~16.67ms for a 60fps device). This value changes if the device drops frames. - When
useFramesis enabled,deltais forced to1 * this.parent.timeScale—meaning each frame contributes exactly 1 "unit" to the tween's progress, regardless of how much real time passes.
What This Means for Your Tween
When useFrames: true:
- The
durationparameter no longer represents milliseconds—it represents total frames the tween will take. In your example, the tween runs for 1000 frames (not 1000ms). - The tween's progress is calculated by counting how many frames have passed, not summing up real-time delta values. So at frame 250, the tween has completed exactly 25% of its duration (250/1000), resulting in the same
xvalue across all devices.
Where Else useFrames Is Used
The useFrames flag propagates to the tween's internal timeline and property steps. For example, in the TweenStep class (which handles individual property animations), the progress calculation uses the adjusted delta value from the parent tween. This ensures every part of the animation adheres to frame-based progression, not real time.
Key Takeaway
useFrames is Phaser's way of making animations deterministic across devices. By swapping real-time delta values for fixed frame-based units, you guarantee that the tween's state will be identical at the same frame count—no matter how fast or slow the device is running.
内容的提问来源于stack exchange,提问作者geeeek

