How to switch scenes in your Phaser game
Hello folks, today you will be learning how to switch scenes in your Phaser game. You will be able to change scenes easily after reading this blog. Also, as a bonus, you will learn how to add smooth fade transition when switching scenes.
โ Note: This code in this blog is only applicable for you, if you have written the code for all the scenes in a single file. But, the main logic for switching scenes is same even if you have different files for different scenes.
Firstly, you need to make sure that you have made scene classes for your scenes and have added those scenes to the config object.
class firstScene extends Phaser.Scene {
// code for the 1st scene
}
class secondScene extends Phaser.Scene {
// code for the 2nd scene
}
const config = {
type: Phaser.AUTO,
scene: [firstScene, secondScene], // the 1st scene is the default scene.
...
};
const game = new Phaser.Game(config);
Then you will need to set a condition for when should you change the scene to the second scene. The condition must be set as per your requirement. It may be when the player gets certain score, when the player wins/loses the game, etc.
The code which you will have to include inside the condition for changing the scenes is given below:
class firstScene extends Phaser.Scene {
if(yourCondition) {
this.scene.start('secondScene');
}
}
Yes, only adding this one line of code will help you change the scene. The syntax for the added code is:
// this shuts down the current scene and runs the given scene
scene.scene.start(key, data);
BONUS:
In order to add a smooth fade transition just before the scene change, you will have to add the code given below:
this.cameras.main.fadeOut(3000); // Fade out the screen
this.cameras.main.once(Phaser.Cameras.Scene2D.Events.FADE_OUT_COMPLETE, () => {
this.scene.start('secondScene');
});
The code given above simply plays fade out animation on the main camera for 3000ms (3s). And once the animation is completed, it changes the scene to the second scene. You can change the time for the fade out animation as per your choice.
๐ And with this, you have learned to switch scenes in your Phaser game with a smooth fade out transition. If you have faced any problems while following this tutorial, feel free to comment below.
Happy Coding! ๐