How to Change Between Scenes in Phaser3

What exactly is a scene in Phaser3?

A scene can be a game level. It can be a menu screen. It could be the title screen. It could be an overworld map or the end game credits.

Your entire game could be one single scene if you wanted.

A scene is simple enough to create. Every example this far has been a scene. But working with multiple scenes can get a little tricky.

But let's jump right to it now. We will start by creating a javascript file. Call it "scene1.js", then edit it and add this code.

class Scene1 extends Phaser.Scene {
	
	constructor () {
		super({ key: 'Scene1' });
	}
	
	create () {
		this.add.text(200, 200, 'Scene1', { fontSize: '50px', fill: '#9999ff' });
	}
}

This class we just defined is a scene. The constructor method contains a way of supplying the "key" or id to this scene.

Now let's make another scene. Create a file called "scene2.js", then edit it by adding this code.

class Scene2 extends Phaser.Scene {
	
	constructor () {
		super({ key: 'Scene2' });
	}
	
	create () {
		this.add.text(200, 300, 'Scene2', { fontSize: '50px', fill: '#9999ff' });
	}
}

Now we have our two scenes. So lets make the main entry point of our game.

Create a new file and this time call it "index.html", and add in this code.

 
<!doctype html> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8" />
    <title>Scene Test</title>
    <script src="phaser.min.js"></script>
    <style type="text/css">
        body {
            margin: 0;
        }
    </style>
</head>
<body>

<script src="scene1.js"></script>
<script src="scene2.js"></script>

<script type="text/javascript">

    var config = {
        type: Phaser.AUTO,
        width: 800,
        height: 600,
        scene: [
            Scene1, Scene2,
        ]
    };
	
	var game = new Phaser.Game(config);
	
</script>

</body>
</html>

Notice now when we launch the index.html file in our web browser, we are greeted with scene1.

To get our game to switch between scene1 and scene2, we need to add a little more code. Edit scene1.js again and add this.

 
class Scene1 extends Phaser.Scene {
	
	constructor () {
		super({ key: 'Scene1' });
	}
	
	create () {
		this.add.text(200, 200, 'Scene1', { fontSize: '50px', fill: '#9999ff' });
		
		this.input.on('pointerup', function () {

                  this.scene.start('Scene2');

                }, this);
	}
}

And inside scene2.js add this.

class Scene2 extends Phaser.Scene {
	
	constructor () {
		super({ key: 'Scene2' });
	}
	
	create () {
		this.add.text(200, 300, 'Scene2', { fontSize: '50px', fill: '#9999ff' });
        
                this.input.on('pointerup', function () {

                  this.scene.start('Scene1');

                }, this);
	}
}

Now when you click the mouse on the game screen, the game switches to the other scene.


Next Topic: Play Two Scenes at the Same Time

Comments

Popular Posts