Phaser.js小游戏重启功能实现遇TypeError问题求助
问题解决:Phaser.js中restartGame函数报错TypeError: undefined is not an object
核心原因
报错是因为restartGame函数里的this指向错误——当把普通函数作为按钮点击回调时,this指向的是触发事件的按钮对象,而非Phaser的场景实例,导致this.physics变成undefined。
三种修复方法
方法1:用箭头函数绑定回调
创建按钮时,用箭头函数包裹重启逻辑,箭头函数会继承外部的this(即场景实例):
// 创建重启按钮示例 this.add.text(200, 50, '重启游戏', { fontSize: '24px', fill: '#ffffff' }) .setInteractive() .on('pointerdown', () => { this.restartGame(); });
方法2:把restartGame定义为箭头函数
将restartGame写成箭头函数,函数内部的this会始终指向场景实例:
restartGame = () => { // 销毁旧玩家(如果存在) if (this.player) this.player.destroy(); // 创建新玩家 this.player = this.physics.add.sprite(100, 450, 'dude'); // 重新设置玩家属性(弹跳、边界碰撞等) this.player.setBounce(0.2); this.player.setCollideWorldBounds(true); // 补充其他必要的初始化逻辑(比如动画、碰撞检测) }
方法3:用bind绑定this到函数
绑定按钮事件时,用bind(this)把场景实例绑定到restartGame函数:
this.add.text(200, 50, '重启游戏', { fontSize: '24px', fill: '#ffffff' }) .setInteractive() .on('pointerdown', this.restartGame.bind(this));
额外建议
别用全局变量存储player,改成场景属性this.player,既方便管理,也能避免全局变量冲突。
内容的提问来源于stack exchange,提问作者Andi Macht
相关产品推荐
相关产品推荐

