PhaserJS中逐字符追加文本遇' '失效问题求助
修复PhaserJS 3逐字符追加文本时换行符失效的问题
问题原因
直接修改Text对象的text属性不会触发Phaser的组件更新流程,导致换行符\n无法被正确解析和渲染。另外代码里存在多余的类型转换,且未在文本追加完成后停止定时事件,可能引发不必要的性能消耗。
修复步骤
- 使用Phaser提供的
setText()方法更新文本内容,该方法会触发组件重绘和布局计算,确保换行符生效 - 移除多余的
parseInt()调用(newText.length本身就是数值类型) - 文本追加完成后停止定时事件,避免无效循环
修复后的代码
function create() { this.savedText = this.add.text(0, 100, "Starting text display") this.newText = "This text should be displayed \n in two lines" this.index = 0 this.timedEvent = this.time.addEvent({ delay: 100, callback: this.onEvent, callbackScope: this, loop: true }) } onEvent() { let textDisplayed = "" if(this.index < this.newText.length) { textDisplayed += this.newText.charAt(this.index) // 使用setText方法替代直接修改text属性 this.savedText.setText(this.savedText.text + textDisplayed) this.index++ // 追加完成后停止定时事件 if(this.index === this.newText.length) { this.timedEvent.remove() } } }
额外提示
如果需要更精细的文本样式控制(比如换行后的缩进、行高),可以在创建Text对象时配置style参数,例如:
this.savedText = this.add.text(0, 100, "Starting text display", { lineSpacing: 8, // 设置行间距 // 若需要自动换行(非硬换行),可添加以下配置 // wordWrap: { width: 400 } })
内容的提问来源于stack exchange,提问作者user22453190
相关产品推荐
相关产品推荐

