Rerun the scene in Phaser 3.

この記事は約4分で読めます。
スポンサーリンク

Things I want to do

Restart the scene in Phaser 3.

For example, restarting the game scene from the beginning when you get a game over.

We will use Part 10 of the Phaser 3 tutorial as an example.

Please refer to the following page for information on downloading the code and comments.

スポンサーリンク

Restart the scene

script

Running the following script will rerun the scene. `this` is the Scene.

Therefore, when calling it from a class that inherits from Scene, you can execute it using the following script.

(In the script, `this.scene` refers to a ScenePlugin, not a Scene class.)

this.scene.restart();

What will happen?

When you call this.scene.restart(), the preload and create methods are called in the same order as the first execution.

However, initialization that takes place outside of preload and create will not be performed.

(When you create a class by inheriting from Scene, the initialization and constructor during member declarations are not called.)

スポンサーリンク

Let’s try using Phaser3 Turtorial.

In the tutorial, you lose input when you get hit by a bomb, but we’ll make it so that you return to the beginning of the scene.

I modified the `hitBomb` function, which is called when a bomb hits, to now call `this.scene.restart();` at the end.

function hitBomb (player, bomb)
{
/*omitted*/ 
    this.scene.restart(); 
}

As a result, the game started again.

However, I cannot input any information, and the game cannot continue.

This is because, as mentioned above, ‘initialization performed outside of preload and create will not be executed.’

We will also initialize the following two values ​​that have not been initialized within the create function.

function create ()
/*omitted*/ 
    score = 0;
    gameOver = false;
}
スポンサーリンク

Result

The scene was able to be restarted.

コメント

タイトルとURLをコピーしました