Game states in Phaser 3

I am new to phaser 3…
How to use game states in phaser 3 . Searching on the web I found this example [http://perplexingtech.weebly.com/game-dev-blog/using-states-in-phaserjs-javascript-game-developement]
which show this ,but it is for phaser 2.

I am not able to convert this to phaser 3.

Thanks in advance.

1 Like

There are no states in phaser 3, they have been replaced with much better Scene system. Scenes are better than states.

If You want to get started with Scenes I recommend You start from reading this guide (from devlogs):


4 Likes

You can also check out the Scene examples to get a feel for how Scenes can be used in Phaser 3.

3 Likes

Thank Ryba and Telinc1.

Found a very good example on using scenes in phaser3 by a user Bdr on this link

I have tried this example ,but it gives me an error.
Uncaught TypeError: this.scene.start is not a function

when I click the playgame button in menu.js file to start the scene gamescene which is in play.js file .

My file structure -

My code :

contents of index.html file -

contents of menu.js file -

var MainMenu = new Phaser.Class({

Extends: Phaser.Scene,

initialize:

function MainMenu ()
{
    Phaser.Scene.call(this, { key: 'mainmenu' });
},

preload: function ()
{
    this.load.image('playgame','assets/play.png');
},

create: function ()
{

    var btn = this.add.sprite(400, 300,'playgame').setInteractive();

    btn.on('pointerdown',function(pointer){
        this.scene.start('gamescene');
    });

}

});

contents of play.js file -

var GameScene = new Phaser.Class({

Extends: Phaser.Scene,

initialize:

function GameScene ()
{
    Phaser.Scene.call(this, { key: 'gamescene' });
},

preload: function ()
{
    this.load.image('bkg','assets/background.jpg');
},

create: function ()
{
    var bg = this.add.sprite(400, 300,'bkg');
}

});

Thanks in advance.

1 Like

The pointerdown event handler on your button is a separate function which runs outside the context of your scene. You can switch to an arrow function ((pointer) => { instead of function(pointer){) because arrow functions don’t have their own context. Alternatively, you can store the value of this in a variable before you define your event handler, then use the variable to refer to you Scene.

3 Likes

Thanks once again Telinc1, problem solved.:smile: