Phaser文本事件无法识别监听函数,游戏黑屏报错求助
问题分析与解决方案
你碰到的这个错误,核心原因是类方法的this绑定丢失了。当你在构造函数里把this.create传给Phaser.Game的配置对象时,这个方法的上下文(也就是this)并没有绑定到你的MyGame实例上。当Phaser调用create方法时,this指向的是Phaser的游戏上下文,而不是你的MyGame对象——这就导致this.onPlay变成了undefined,所以Signal的add()方法才会报错说“listener不是函数”,连带游戏启动后因为报错中断了初始化,出现黑屏。
下面给你两种靠谱的修复方案:
方案1:在构造函数中手动绑定方法的this
修改构造函数,把preload、create、update这些方法的this绑定到当前MyGame实例上:
class MyGame { game: Phaser.Game; textStyle: object = { font: "Ubuntu", fill: "black", align: "center" }; constructor() { // 绑定方法的this到当前实例,避免上下文丢失 this.preload = this.preload.bind(this); this.create = this.create.bind(this); this.update = this.update.bind(this); this.onPlay = this.onPlay.bind(this); // 提前绑定回调也可以 this.game = new Phaser.Game(800, 640, Phaser.AUTO, 'content', { preload: this.preload, create: this.create, update: this.update }); } preload() { } create() { this.game.stage.backgroundColor = "#eee"; let buttonPlay = this.game.add.text(this.game.world.centerX, this.game.world.centerY, "play", this.textStyle); buttonPlay.anchor.setTo(0.5); buttonPlay.inputEnabled = true; buttonPlay.events.onInputUp.add(this.onPlay, this); } update() { } onPlay() { console.log("pressed play"); } }
方案2:用箭头函数定义类方法(TypeScript友好)
箭头函数会自动捕获当前上下文的this,你可以把create、preload这些方法改成箭头函数形式,省去手动绑定的步骤:
class MyGame { game: Phaser.Game; textStyle: object = { font: "Ubuntu", fill: "black", align: "center" }; constructor() { this.game = new Phaser.Game(800, 640, Phaser.AUTO, 'content', { preload: this.preload, create: this.create, update: this.update }); } // 用箭头函数定义方法,自动绑定this preload = () => { } create = () => { this.game.stage.backgroundColor = "#eee"; let buttonPlay = this.game.add.text(this.game.world.centerX, this.game.world.centerY, "play", this.textStyle); buttonPlay.anchor.setTo(0.5); buttonPlay.inputEnabled = true; buttonPlay.events.onInputUp.add(this.onPlay, this); } update = () => { } onPlay = () => { console.log("pressed play"); } }
两种方案都能让create方法里的this始终指向MyGame实例,this.onPlay也就会是有效的函数,Signal的add()方法就能正常工作,黑屏的问题也会跟着解决。
内容的提问来源于stack exchange,提问作者frostbyte
相关产品推荐
相关产品推荐

