Phaser 3临时文本框实现遇阻,能否使用for循环解决?
解决Phaser 3中文本短暂显示后消失的问题
原代码的核心问题
- 计时器重复重置:每次进入
bought == true分支时,shockTime1和shockTime2都会被设为0,导致shockTime1永远只能自增到1,下一次帧更新又被重置,第一段对话一直显示。 - 条件逻辑矛盾:第二个
else if的判断条件this.shockTime2 == 100 && this.shockTime2 < 100永远不可能成立,第二段对话永远无法触发。 - 变量名错误:代码中误用
this.thankTime2,正确变量应为this.shockTime2。
为什么不能用for循环解决?
Phaser是基于帧循环的游戏框架,for循环会在单帧内完成所有迭代,不会等待时间流逝。用for循环的话,文本切换会瞬间完成,完全达不到“短暂显示”的效果,甚至会阻塞游戏线程导致报错。
正确实现方式
方式1:在update函数中管理对话状态(适合精确帧控制场景)
// 场景初始化时配置状态变量 create() { this.bought = false; this.dialogueState = 0; // 0: 无对话, 1: 显示第一段, 2: 显示第二段, 3: 结束 this.shockTimer = 0; // 初始化bubble和speech文本框... } update() { if (this.bought && this.dialogueState !== 3) { this.shockTimer++; switch(this.dialogueState) { case 0: // 启动第一段对话 this.bubble.setAlpha(1); this.speech.setText('What the heck?! \nYou used company\nmoney to buy some\nrun down mansion?\nWhy?!?'); this.dialogueState = 1; break; case 1: // 第一段显示100帧后切换 if (this.shockTimer >= 100) { this.speech.setText('You\'re not going to\neven live there! This is\nan outrageous waste\nof money! You \nlittle idiot!!!'); this.dialogueState = 2; this.shockTimer = 0; // 重置计时器 } break; case 2: // 第二段显示100帧后结束 if (this.shockTimer >= 100) { this.bubble.setAlpha(0); this.speech.setText(''); this.dialogueState = 3; this.bought = false; // 避免重复触发 } break; } } }
方式2:使用Phaser内置计时器事件(更简洁,推荐)
Phaser的time.delayedCall可以在指定时间后执行回调,无需在update里轮询:
// 触发购买逻辑的地方(比如按钮点击事件) handleBuy() { if (this.bought) return; this.bought = true; this.bubble.setAlpha(1); // 显示第一段对话,100帧后切换(假设帧率60,100帧≈1.67秒) this.speech.setText('What the heck?! \nYou used company\nmoney to buy some\nrun down mansion?\nWhy?!?'); this.time.delayedCall(Phaser.Time.Timer.SECOND * (100/60), () => { // 切换到第二段对话 this.speech.setText('You\'re not going to\neven live there! This is\nan outrageous waste\nof money! You \nlittle idiot!!!'); // 再100帧后隐藏文本框 this.time.delayedCall(Phaser.Time.Timer.SECOND * (100/60), () => { this.bubble.setAlpha(0); this.speech.setText(''); this.bought = false; }); }); }
内容的提问来源于stack exchange,提问作者EmptyStone
相关产品推荐
相关产品推荐

