You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 12:53:15