Changing scene on click

Hello, I am trying to implement a couple of scenes in my game in order to understand them, what I am trying to do is navigate from my first scene MainMenu to a second EntryLevel when the user clicks on a play button, I have tried this which does not work:

class MainMenu extends Phaser.Scene {

constructor() {

    super('bootGame')

}

preload() {

    this.load.image('menuBackground', 'assets/world/menubackground.png');

    this.load.image('play_button', 'assets/world/play_button.png');

    this.load.audio('menu_music', 'assets/music/menu_music.mp3');

}

create() {

    this.add.image(400, 300, 'menuBackground');

    var playButton = this.add.image(this.game.renderer.width / 2, this.game.renderer.height / 3, 'play_button').setDepth(1);

    playButton.setInteractive();

    playButton.on('poninterdown', function () {

        this.scene.start('entryLevel')

    }, this);

    this.sound.play('menu_music', {

        loop: true

    });

}

}

And I also tried this that at least hooks on the click event but when I click the button I get this error: this.scene.start is not a function, here is the code:

class MainMenu extends Phaser.Scene {

constructor() {

    super('bootGame')

}

preload() {

    this.load.image('menuBackground', 'assets/world/menubackground.png');

    this.load.image('play_button', 'assets/world/play_button.png');

    this.load.audio('menu_music', 'assets/music/menu_music.mp3');

}

onObjectClicked() {

    this.scene.start('entryLevel')

}

create() {

    this.add.image(400, 300, 'menuBackground');

    var playButton = this.add.image(this.game.renderer.width / 2, this.game.renderer.height / 3, 'play_button').setDepth(1);

    playButton.setInteractive();

    this.input.on('gameobjectdown', this.onObjectClicked);

    this.sound.play('menu_music', {

        loop: true

    });

}

}

How can I change the scene when I click the play button correctly?

Turns out it was a scoping issue, fixed it like this:
const self = this;

    this.input.on('gameobjectdown', function () {

        self.scene.start('entryLevel');

    });

Glad you solved it.

Just as a small improvement, you can avoid the use of self (which is sort of an antipattern) you could register the event listener like this:

 this.input.on('gameobjectdown', this.onObjectClicked, this);

The last parameter of the on function is the scope or context where you want the listener to be executed on.

And for the sake of completeness, I think the problem with your first try is that 'poninterdown' is misspelled.

1 Like

EDIT: Never mind I saw that @glantucan already spotted it, sorry.

Not sure if you’re still uding the initial example you provided but I notice you spelled pointerdown incorrectly as ‘poninterdown’