Episode 4: States and everything about them

In this lesson we’re going to learn how to create states, extend them and also how to control them

You can create states using two methodologies. First one, the one I’m going to use, is called object literal. You can check all previous examples on Github to see what I’m writing about.

This is very basic example of a state using this notation:

var MyGame = {};
MyGame.StateExample = function (game) {
this.someObject = null;
};
MyGame.StateExample.prototype = {
preload: function () {
// Load your stuff
},
create: function () {
// Create objects
}
};

Second method is used mainly when you want to code a game in TypeScript or something similar. If you want to know more about this topic please check some examples available online.

Adding state

To add a state (after loading js file with it) you need to use this code:

game.state.add('StateExample', MyGame.StateExample, true);

To view documentation of this function please follow this link.

Important! Third argument tells Phaser to start a state immediately.

Starting states

To start a previously added state simply run this code:

this.state.start('key');

Key is first argument when using game.state.add.

Here’s order of what’s happening on state change:

  1. state.shutdown on current sate is fired.
  2. Tweens are removed.
  3. Camera and Input Manager are being resetted.
  4. Physics systems cleanup.
  5. Timer are related event are being removed.
  6. Reset of a Scale Manager.
  7. Reset of a Debug Module.
  8. If clearWorld was true all objects are being removed from the world (check source here).
  9. Same with cache and the clearCache argument (check source here).
  10. New state starts 🙂

Restarting states

Actually this works the same as this.state.start(‘key’) but it starts current state from the beginning. It even takes the same args clearWorld and clearCache.

To restart state use:

this.state.restart();

Dynamic states

You can add your states during program run. In fact this might be a good idea to not store all states at once in a large application. It is very good practice to load game state files while user plays your game.

No examples this time because states are fairly easy 🙂