Ad

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.

Ad

Answer

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.

Ad
source: stackoverflow.com
Ad