Phaser3 + ES6 类:如何保持作用域从创建到更新

Phaser3 + ES6 classes : how to keep the scope from create to update

我是 Phaser 3 开发的初学者,我正在尝试为我的所有游戏定义一个好的模式。我找到了很多优秀的单页教程,但是当我在 ES6 类 系统中翻译它们时,我遇到了范围问题(在 create() 中定义的元素在更新中不可见)。

我看到没有 ES6 类 的一种常见模式是在游戏配置对象的场景 属性 中添加方法,如下所示:

scene: {
    preload: preload,
    create: create,
    update : update
}

下面是我的问题。如果我有这个代码:

window.onload = function() {
    const config = {
        width: 1136,
        height: 640,
        backgroundColor: "#ECF0F1",
        scene: bootGame
    }
    jeu = new Phaser.Game(config);

    class bootGame extends Phaser.Scene{
        constructor(){
            super("BootGame");
        }
        preload(){}
        create(){    
            let cursors = this.input.keyboard.createCursorKeys();
        }
        update(){
            if (cursors.left.isDown){// cursors not defined}
        }
     }

我应该写什么才能在 update() 中定义 "cursors"?

非常感谢您的帮助!

PS:我看过那个问题 但它是 Typescript + import module 语法让我迷路了。

bootGame 是 class 而在 class 中 this 指的是 class。因此,您需要创建 this.cursors 使其成为 class 的 属性 并且同一 class 中的每个方法(函数)都可以通过以下方式访问 属性 this.cursors.

当您使用 let 定义变量时,它的范围仅限于定义它的块。在这里,您在 create 函数中定义了 cursors,因此无法在外部访问它create 函数。