The purpose
This explains how to restart a scene in Phaser 3.
For example, this is useful for restarting a game scene from the beginning after a game over.
We’ll use Phaser 3 Tutorial Part 10 as a reference.
The code download and comments are available on the page linked below.
Restart Scene
Script
Executing the script below will restart the scene. this
refers to the Scene.
Therefore, this script can also be executed when called from a class inheriting from Scene.
(Note that this.scene
within the script refers to the ScenePlugin, not the Scene class.)
this.scene.restart();
What is happen
Calling this.scene.restart()
will invoke the preload
and create
methods sequentially, just as they were during the initial execution.
However, any initialization performed outside of the preload
and create
methods will not be repeated.
(If you create a class inheriting from Scene, member initialization during declaration and the constructor will also not be called.)
Use for Phaser3 Turtorial
The tutorial would become unresponsive upon hitting a bomb, but I’ve made it return to the beginning of the scene.
I fixed this by adding this.scene.restart();
to the end of the hitBomb
function, which is called when a bomb is hit.
function hitBomb (player, bomb)
{
/*略*/
this.scene.restart();
}
As a result, the game started again.
However, I can’t input anything and the game won’t continue.
This is because the initialization that’s performed outside the preload
and create
functions (above) isn’t happening.
To fix this, I will also initialize the following two values, which aren’t initialized within create
.
function create ()
/*omitted*/
score = 0;
gameOver = false;
}
Result
We are able to restart the scene.
comment