phaser-frameworkpauseresume

how can i change text when pausing / resuming phaser game?


I'm trying to toggle between 'Pause' and 'Resume' text when pausing and resuming, i tried the following in create:

gameState.playPauseText = this.add.text(660, 547, 'Pause', { fontFamily: 'Roboto Mono, monospace', fontSize: '20px',  fill: '#FFFFFF' });

then tried changing that inside a callback function:

gameState.playPauseArea.on('pointerdown', () => {
        if(!gameState.isPaused) {
            gameState.playPauseText.setText('Resume');
            game.loop.sleep();
            gameState.isPaused = true;

        }
        else {
            gameState.playPauseText.setText('Pause');
            game.loop.wake();
            gameState.isPaused = false;
           
        }
    });

then i tried same, but changed .setText to .text =. The best i got from all above is to change text to 'Resume' after 2 clicks, but never back to 'Pause'.

I also tried the following in update:

if(gameState.isPaused) {
        gameState.pauseText.setText('Resume')
        

    } else {
        gameState.pauseText.setText('Pause');
       
    }

that didn't do anything.

I also tried creating two separate texts and hiding one with setVisible(false) and tried all of the above toggling both 'Resume' and 'Pause' between setVisible(true) and setVisible(false).

also nothing.

I use .setText() somewhere in my code, to change score text and it works fine.


Solution

  • The problem is, that you are stopping the game loop, so nothing is going to be painted/updated any more. You could call the game.loop.sleep() with abit of delay, so that a repaint, will still be triggert.

    ...
    setTimeout( () => game.loop.sleep(), 50);
    ...
    

    Or with the Phaser delayedCall function:

    ...    
    this.time.delayedCall(50, game.loop.sleep, null, game.loop);
    ...
    

    here a short demo:

    document.body.style = 'margin:0;';
    
    var config = {
        type: Phaser.AUTO,
        width: 536,
        height: 183,
        scene: {
            create
        },
        banner: false
    }; 
    
    function create () {
       let text = this.add.text(30, 90, 'Click me to start');
       let pause = false;
       
       this.input.on('pointerdown', () => {
        if(!pause) {
                text.setText('Click me to Resume');
                setTimeout( _ => game.loop.sleep(), 50);
                pause = true;
    
            }
            else {
                text.setText('Click me to Pause');
                game.loop.wake();
                pause = false;
               
            }
       })
    }
    
    let game = new Phaser.Game(config);
    <script src="https://cdn.jsdelivr.net/npm/phaser@3.55.2/dist/phaser.js"></script>