How to pause/unpause game Phaser 3

Hi guys,
I am working on a game right now and I want to be able to pause and unpause the game using the ‘p’ key and have the text ‘Paused’ in the center of the screen, but I don’t know how to go about it. If anyone could help, that would be great.

1 Like

Hi there!
I don’t know if there is a default function for that, but you could do it in the update function of the scene:

let pause = false;

update(){

    if(p is pressed) pause = !pause;

        if(pause){
            return;
        }
// your code here
}

You make a global variable or scene variable to hold the pause state (let pause = false)
Then you check if the button p is pressed. If yes, then you toggle the pause value (pause = !pause).
If the game is paused, the update loop will not proceed after

if(pause){
    return;
}

As for the text, you can either use the text method or use an image.

Hi!

I’m happy creating a scene for my game and other scene for my pause screen.

this.scene.pause("GameScene");
this.scene.launch("PauseScene");

This way allows me to stop game and its logic easily, without complications.

Happy coding!

2 Likes

Thanks for the advice, @Manz. How would I toggle between the pause scene on differences scenes? Like if I had more than one Game scene?

Hey @Eliaquim. I appreciate the advice, but I find it kind of confusing. How would I declare a global variable? And how would I toggle between the two scenes (pause and my game scene) with the same key?

Hi!
In my example, you do not need to have another scene.
You can declare the global variable at the init or create function of the scene:

this.isPaused = false;

And to change the boolean value of this.isPaused, you only have to check:
if( button P is pressed) this.isPause = !this.isPause;

which is the same as

if(button P is pressed){
    if(this.isPause)
        this.isPause = false
    }else{
        this.isPause = true
    }
}

Hi @Eliaquim. That really help me out. Thanks! I was able to pause my game scene, but is there a way to unpause using the same p key?

Hi! ^^
Yes for sure, with that same code I gave to you. But you have to put it at the top of your update function:

update(){

    if( button P is pressed) this.isPause = !this.isPause;

    if(this.isPause) return; // That will stop your update function

    // Your code here

};

Thanks!

1 Like