Episode 1: Intro to state manager

States in other words are chunks of game program – think of them as chapters. States are not something you see, they are only containers with variables and renderable objects. For example preloader or main menu can have a state. Also levels of your game are states, even game over screen can be a state. In opposition to this power up and player are not states.

You should not put all code in one file. It is hard to maintain and debug. Every state can be put into separate file for clearness.

Please remember that you can have only one active state at one time. Many states are stored in state manager but only one is running.

This example shows how to load states from separate files and add them to state manager:

<script src="js/vendor/phaser.min.js" type="text/javascript"></script>
<script src="js/preloader.js" type="text/javascript"></script> 
<script src="js/menu.js" type="text/javascript"></script>

In the same html file add this JavaScript:

game.state.add('Preloader', MyGame.Preloader);
game.state.add('Menu', MyGame.Menu);

This is source for preloader state:

var MyGame = {};

MyGame.Preloader = function(game) {
};

MyGame.Preloader.prototype = {
 preload : function() {
 // Load assets.
 this.load.image('background', '../assets/sky.png');
 this.load.image('logo', '../assets/logo.png');
 },
 create : function() {
 // Start next state.
 this.state.start('Menu');
 }
};  

It simply preloads two images and runs next state which is Menu. When preload function is complete it triggers create.

Here is menu source:

MyGame.Menu = function(game) {
 /**
 * Declare vars
 */
 this.background;
 this.logo;
};

MyGame.Menu.prototype = {
 create : function() {
 
 // Add sprites to scene
 this.background = this.add.sprite(0, 0, 'background');
 this.logo = this.add.sprite(game.world.centerX, game.world.centerY, 'logo');
 
 // set sprite anchor to 0.5
 this.logo.anchor.setTo(0.5);
 
 // set sky to full game screen
 this.background.height = game.height;
 this.background.width = game.width;
 }
};

Please check an API documentation for Sprite constructor used in this example to determine how it works and how to set its anchor.

Result:

Result of working code
Result of working code

Git repository:

You can visit my Github to download source code of examples.