Phaser 3重启场景后文本不跟随玩家的问题与解决
Phaser 3 重试场景后计时文本不跟随玩家的解决方案
问题描述
使用Phaser 3开发的游戏包含gameScene(游戏场景)和timeTrialEnd(结果场景)两个场景。点击结果场景的重试按钮后,游戏可正常重启,但计时文本不再跟随玩家移动,固定停留在玩家触发终点旗帜时的位置。
问题核心代码
class gameScene extends Phaser.Scene{ preload(){ gameScene.seconds = 0 this.interval = setInterval(counter, 1000); } create(){ gameScene.Text = this.add.text(this.player.x+50, this.player.y-50, { fontSize: '16px', fill: '#fff' }); gameScene.Text.setText(0); } update(){ gameScene.Text.x=this.player.x+50 gameScene.Text.y=this.player.y-50 } } function counter(){ gameScene.seconds = gameScene.seconds+1 gameScene.Text.setText(gameScene.seconds) }
问题原因
原代码将计时变量seconds和文本对象Text绑定在gameScene类本身而非场景实例上,同时使用外部独立的counter函数,导致场景重启后,定时器和文本引用仍指向旧场景实例的内容,新场景的update逻辑无法正确控制新文本的位置。
修复方案
将计时逻辑移入create函数,使用箭头函数确保this指向当前场景实例,把所有相关变量改为场景实例属性,删除preload中的定时器及外部counter函数。
修复后完整核心代码示例:
class gameScene extends Phaser.Scene{ preload(){ // 仅保留资源加载逻辑,移除定时器初始化 } create(){ this.seconds = 0; // 创建计时文本并绑定为实例属性 this.timerText = this.add.text(this.player.x+50, this.player.y-50, { fontSize: '16px', fill: '#fff' }); this.timerText.setText(0); // 使用箭头函数创建定时器,确保this指向当前场景实例 this.interval = setInterval( () => { this.seconds = this.seconds + 1 this.timerText.setText(this.seconds) },1000); } update(){ // 更新实例属性的文本位置 this.timerText.x = this.player.x + 50 this.timerText.y = this.player.y - 50 } }
关键修改点
- 把
preload中的定时器初始化移到create阶段,符合Phaser场景生命周期规范 - 使用箭头函数创建定时器,保证
this始终指向当前场景实例 - 将
gameScene.seconds、gameScene.Text改为实例属性this.seconds、this.timerText,避免不同场景实例间的变量污染 - 删除外部
counter函数,将计时逻辑内联到箭头函数中,确保上下文正确
修改后,重试场景时,新的场景实例会创建独立的计时文本和定时器,update函数能正确更新文本位置,跟随玩家移动。
内容的提问来源于stack exchange,提问作者Genesis cookie
相关产品推荐
相关产品推荐

