How to pause/unpause game on a single event handler

I have this pause key:

pauseKey = game.input.keyboard.addKey(Phaser.KeyCode.P);
pauseKey.onDown.add(this.pauseUnpauseGame);

which calls this method when P key is pressed down:

pauseUnpauseGame: function () {
    if(gameObject.paused) {
          gameObject.paused = false;
          createRotatingBackground.data.resume();
          pauseMenu.visible = false;
     } else {
          gameObject.paused = true;
          createRotatingBackground.data.pause();
          pauseMenu.visible = true;
    }
}

which should pause the game if playing and resume game if paused. Also stop level background from rotating or start rotating and display pause menu if game is paused and hide it if game is resumed.

But I get an error:

Uncaught InternalError: too much recursion

Is it possible to make all this functionality in one pause/unpause method, instead of two? Because then I will need to use two keyboard keys, say, R and P which are a bit far from each other.

Open the stack trace for that error, if there is one.

The lines of recursion are the ones with

gameObject.paused = false;

and

gameObject.paused = true;

As if the code was calling the pauseUnpauseGame() method each time game was pause or resumed

Is gameObject the Phaser.Game? What is createRotatingBackground.data?

I see I cannot edit the post now, but never mind.

  • Yes, gameObject is just another name in my code for Phaser.Game.
  • And createRotatingBackground is an object of type Phaser.Group holding two instances of Phaser.Image which is the background image.
  • I see Phaser.Group doesn’t have the “data” sub-object but then JavaScript is flexible enough to add it on its own. I was thinking on abusing the data sub-object which exists in Phaser.Graphics to add data and helper methods without using Phaser.Utils.mixin() and mixinPrototype(). But then JavaScript is smart enough to create data sub-object on its own. Consider it just unnecessary method of adding functionality :slight_smile:
  • pause() and resume() methods in the createRotatingBackground are methods that are called inside Phaser.State.update() which control if the rotating background should start moving and what to happen when the first bg. image crossed the screen scrolling towards left and what to happen when the second bg. image crossed the screen scrolling towards left

Since I added separate gamePaused boolean flag and not using Phaser.Game.paused flag at all, I was able to overcome the recursion problem. But if necessary I am able to reproduce the problem again.
It seems, setting Phaser.Game.paused = false in a method that was called when onPause event was called causes the recursion.

I have these too:

game.onPause.add(this.pauseUnpauseGame);
game.onResume.add(this.pauseUnpauseGame);

Just curious, maybe I will try recreate the problem… :slight_smile:

Remove those.