Using variables from create in the update function Phaser 3

Viewed 20

In my game I am trying to use one of my variables I have initiated in my create function outside of that scope and to be used in the update function. Ideally my code would look like this:

create()
    {
       const map = this.make.tilemap({ key: 'mainmap' })
       const tileset = map.addTilesetImage('Serene_Village_16x16', 'tiles', 16, 16, 1, 2)

       const Next1 = map.createLayer('Next', tileset)

update(t: number, dt: number){       
        
    this.physics.world.collide(this.faune, Next1, ()=>{
        console.log("testing")
        this.scene.stop(),
        this.scene.start('secondmap');
        });

The problem with this however is that I can not access next1 to collide with my player character "faune" since the error given is that I "Cannot find name 'Next1'.". If anyone has any idea how to use this across functions with Phaser that would be extremely helpful.

Thanks, arthur

1 Answers

The problem is that you are defining the function Next1 in the create function and trying to access it in the update function.
you could, simply in create define a property, like this:

this.next1 = map.createLayer('Next', tileset)

and in the update function, use it like this:

this.physics.world.collide(this.faune, this.next1, () => { 
    // ...
});

for this not to through a compiler error, when using typescript you would have to add the property to the class definition.

class myScene extends Phaser.Scene {
    // you can use the exact datatype if you know it
    public next1:any; 
    ...
}

Or simply put the this.physics ... code into the create function.

Related