Phaser 3页面切屏/最小化时定时器与动画不同步问题求助
React + Phaser 3.80.1 窗口切换时动画与定时器不同步问题
我在React项目中使用Phaser 3.80.1开发带有定时器的动画,遇到以下问题:当通过Alt-Tab切换窗口或最小化页面时,动画会停止运行,但定时器仍在继续,最终导致GameObject与定时器状态不同步。
已尝试的解决方案
- 查阅Phaser的GameConfig配置类,未找到相关控制参数
- 监听页面可见性变化并调用
this.game.loop.wake(),无效,切出页面后动画仍会停止:
create() { //[...] this.setupVisibilityChangeListener(); } setupVisibilityChangeListener() { document.addEventListener('visibilitychange', () => { this.game.loop.wake(); }); }
- 监听Phaser游戏的
visible/hidden事件,分别调用resume()/pause(),问题未解决:
this.game.events.on('visible', () =>{ this.game.resume() }); this.game.events.on('hidden', () => { this.game.pause() });
补充信息
游戏初始化配置(React useEffect中)
useEffect(() => { //[...] const config: Phaser.Types.Core.GameConfig = { type: Phaser.AUTO, parent: 'phaser-container', width: width, height: height, transparent: true, scene: [new RaceScene(data, isMobile)], physics: { default: 'arcade', arcade: { debug: false, fps: 30, }, }, fps: { target: 30, forceSetTimeOut: true, }, input: { touch: { capture: false, }, }, } const game = new Phaser.Game(config) //[...] })
时间同步实现
通过Phaser场景的update函数的time参数获取时间,再通过EventEmitter发送给React:
import animationEventEmitter from '<path>/animation.event' update(time: number, delta: number): void { //[...] animationEventEmitter.emit('timeUpdate', time) //[...] }
EventEmitter代码
import { EventEmitter } from 'events' const animationEventEmitter = new EventEmitter() export default animationEventEmitter
- 使用的是npm安装的
Phaser 3.80.1 - 项目中未使用任何setTimeout/setInterval或delay逻辑
内容的提问来源于stack exchange,提问作者A.J Alhorr
相关产品推荐
相关产品推荐

