Turn on/off debug at runtime?

Is there a way to turn on and off GameConfig’s physics.arcade.debug at runtime?

 physics: {
    default: 'arcade',
    arcade: {
      debug: true,
      gravity: { y: 0 }
    }
  }

Reviving this topic since I haven’t seen this question answered yet.

The debug features seems to be handled by the Phaser.Physics.Arcade.World class. Each scene using Arcade Physics will have an instance of this class accessible through the scene property physics.world (within your scene, you’d write this.physics.world)

When the game config property physics.arcade.debug is set to true, Phaser creates a graphics object that it uses to draw all its debug graphics using the method createDebugGraphic() from the Phaser.Physics.Arcade.World class. This graphics object is stored in the scene’s physics instance at physics.world.debugGraphic. It also sets the property physics.world.drawDebug to true. To turn the debug graphics off, all you’d have to do is set physics.world.drawDebug to false somewhere in your scene.

The catch is that it will stop re-drawing the graphics object to match your physics bodies, but it won’t clear the debugGraphic graphics object, so the instant you set drawDebug to false, all your debug graphics will freeze exactly where they are but won’t disappear. To clear them, you have to call the clear() method on the debugGraphic object. To turn them on again, just set drawDebut to true again.

The second catch is that if you set config property physics.arcade.debug to FALSE, Phaser never calls createDebugGraphic to create the debugGraphic object, so setting drawDebug to true in this case would throw an error because it would be trying to access a graphics object that doesn’t exist.

You have two options here:

  1. Set the config property physics.arcade.debug to true, and then in the create method of your scene, set this.physics.world.drawDebug to false. Now you can turn it on and off whenever you want because the debugGraphic object was created on boot.
  2. If for some reason you can’t or don’t want to set debug to true in the game config, you can manually call physics.world.createDebugGraphic() at any time which will instantiate a graphics object to physics.world.debugGraphic and then you can do the same as above.

For a concrete example of how I turn my physics debug on and off:

gameConfig = {
  ...
  physics: {
    arcade: {
      debug: true
    }
  }
  ...
}

// in my scene class
create() {
  this.physics.world.drawDebug = false;
  this.toggleDebug = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.P);
}

update() {
  if (Phaser.Input.Keyboard.JustDown(this.toggleDebug)) {
    if (this.physics.world.drawDebug) {
      this.physics.world.drawDebug = false;
      this.physics.world.debugGraphic.clear();
    }
    else {
      this.physics.world.drawDebug = true;
    }
  }
}
1 Like