Exploring Phaser 3 with a Game: Adding Multiple Scenes

In part one we had made peg solitaire game in Phaser 3 which was a single scene game. We will further explore Phaser 3 and use multiple scenes. Most of the times games would have a menu screen and a separate game screen. Many games would also keep a separate screen once the game is over so let us make changes in our game to add another scene which will be called once the game is over (either game is finished or there are no further moves).

We are going to define our “game over” scene as following

Game over scene simply displays a “game over” message and total number of moves it took to finish. In case of “no win” we can also display no of pegs remaining. In “preload” method of this scene we are loading “restart” image which will be used for restart button and attached with the “pointerup” event. Once that event is called, we will remove the current scene and begin the game scene. The scene will be automatically started for which the third parameter in this.scene.add method will be passed as “true”.

Also notice the way we pass data between the scenes. We use global registry and save data in the “game scene” which can be retrieved using the same key in the “game over” scene (we are using ‘gamedata’ as key here).

Now we need to make some changes in the game code as well to check for “game over”, and then start “game over” scene once the game is over.

In the game scene we have added a text label to display number of moves made in the game and also a check for a valid move in the game. If no valid move is found then we simply call the gameover method which does similar thing which we did in the “game over” scene. It removes current scene and then starts “game over” scene. On gameover we also save data to the registry which we need to pass to the next scene. Note that we don’t have to start all scenes at once. We can start a scene when needed and we also don’t have to keep scenes in the memory. Scenes can be removed and then launched again when needed.

So far the code can be seen at work here


Leave A Comment

Your email address will not be published. Required fields are marked *