Phaser 3中Game.update方法报cursors is not defined错误的问题求助
Phaser 3中Game.update方法报cursors is not defined错误的问题求助
问题分析
这个错误的根源很明确——变量作用域不匹配。你在Game类的create()方法里定义的cursors和player都是局部变量,它们的作用域只限于create()方法内部。而update()是类的另一个独立方法,根本无法访问到这些局部变量,所以会抛出“未定义”的错误。你之前尝试改成全局变量没生效,大概率是全局变量的声明方式不对,或者没有正确绑定到类的上下文里。
解决方案
解决这个问题的核心是把需要跨方法共享的变量改成类的实例属性,也就是用this.前缀来定义,这样整个类的所有方法都能通过this访问到这些变量。
修改后的Game.js代码如下:
export class Game extends Scene { constructor () { super('Game'); this.W = window.innerWidth; this.H = window.innerHeight; // 提前声明实例属性(可选,但能让代码更清晰) this.player = null; this.cursors = null; } create () { // 用this.定义player,变成实例属性 this.player = this.add.rectangle(this.W / 2, this.H / 2, 25, 25, 0xfafafa); this.physics.add.existing(this.player); // 同样用this.定义cursors this.cursors = this.input.keyboard.createCursorKeys(); this.cameras.main.setBackgroundColor(0x0a0a0a); } update () { // 通过this.cursors和this.player访问变量 if (this.cursors.left.isDown) { this.player.body.setVelocityX(-20); } // 额外补充:建议添加松开方向键时重置速度的逻辑,不然玩家会一直移动 else if (this.cursors.right.isDown) { this.player.body.setVelocityX(20); } else { this.player.body.setVelocityX(0); } } }
额外提示
在Phaser的场景开发中,所有需要在create()、update()或者其他自定义方法之间共享的变量,都应该用实例属性(this.xxx)来管理,这是最规范且不易出错的方式。避免使用全局变量,不仅容易引发命名冲突,还会让代码的可维护性变差。
内容来源于stack exchange
相关产品推荐
相关产品推荐

