How to Play Two Scenes Simultaneously in Phaser3

What if we want two scenes to play at the same time in Phaser3?

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' });
	}
}

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 play both scenes at the same time, we need to add a little more code. Edit scene1.js again and add this to launch the second scene.

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

Now when we launch the index.html file in our web browser, we can see both scenes running parallel, at the same time.

Next Topic: Adding Music to a Game

Comments

Popular Posts