简体   繁体   中英

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

I'm a beginner in Phaser 3 dev and I'm trying to define a good pattern for all my games. I found a lot of excellent one-page tutorials but when I translate them in the ES6 classes system, I'm having a hard time with scope issue (elements defined in create() aren't visible in update).

I've seen that one common pattern without ES6 classes is to add the methods in the scene property of the game config object like this :

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

Now here's my question. If I have this code :

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}
        }
     }

What should I write to get "cursors" to be defined in update() ?

Many thanks for your help!

PS: I've seen that question Phaser + Typescript losing scope in update but it's Typescript + import module syntax gets me lost in the way.

bootGame is class and in class this refers to that class. So, you need to create this.cursors so it becomes the property of that class and every method(function) in the same class can access that property by this.cursors .

When you define variable with let it's scope is limited to the block it is defined in. Here, you have defined cursors in create function so it cannot be accessed outside create function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM