Search code examples
menuphaser-frameworkscene

Phaser 3 can't get the start method to work right


I'm trying to make a menu where the scene changes when the player clicks a button using the start method. At first, I had it all in the create function with this:

var levelOne = this.add.sprite(200, 400, 'LevelOne').setInteractive();

    levelOne.on('pointerdown', function (pointer) {

      this.scene.start('play');
      
  });

But this led to an error in which it said that this.scene.start isn't a function.

I looked at a previous example where the method worked, the big difference was that the method was in the update function, so I rewrote my code to have this in the create function:

this.choice = 0;

    var levelOne = this.add.sprite(200, 400, 'LevelOne').setInteractive();

    levelOne.on('pointerdown', function (pointer) {

      this.choice = 1;
      //game.settings = {
        //gameTimer: 60000    
      //}

  });

And this in the update function:

if (this.choice == 1){
    this.scene.start('play'); 
}

Sadly, this didn't work either and didn't even give an error message. I can't tell what went wrong. Please help.


Solution

  • You have to pass the scene as the context to the event function on(...) (link to the documentation), as the third parameter, so that you can access the scene properties and functions in the event callback.

    levelOne.on('pointerdown', function (pointer) {
        this.scene.start('play');    
    }, this); // <-- you have to add "this"