Phaser for Beginners

Understanding Phaser states

Although managing Phaser states is an advanced feature, it’s very important to learn how to use states from the beginning of your Phaser programming course, as they will allow you to write better code and have a better resource management. You are going to understand this important feature while you are making your first game.

Let’s think about a game, one of the games you are playing these days. Although I don’t know which games you are playing, I bet they all have at least a title screen, a screen with the game itself, and a game over screen. Each “screen” can be developed as a Phaser state, which can be executed cleaning memory and resources before it starts, allowing us to easily switch through game “screens”. To create the first state, add these lines to game.js:

Launch the game again, and this is what you should see in the console:

What did we do? Let’s have a look at the code, line by line:

Here we assign a function to a variable called playGame . We also pass game variable to the function.

A variable passed as parameter inside a function is called argument. Arguments are passed to a function by placing them between the parentheses. Functions can have any number of arguments, separated by commas.

We are about to define the prototype of the previously declared playGame variable.

Every JavaScript object has a prototype. The prototype itself is also an object, and all JavaScript objects inherit their properties and methods from their prototype.

Then we have another function:

Inside playGame object we have a function called create. This is a reserved name used by Phaser to know which function to execute once the state has been called.

A function inside an object is called method. For the same reason, when we refer to an object method, we mean a function declared inside the object itself.

Inside the function we just output something to browser console.

console.log(text) will output the content of text in your browser console. Not all browsers support console.log , but Google Chrome does.

Finally we can talk about the main topic of this section, Phaser states:

Here is how we add a state to our game. The first parameter – from now on argument as said before – is the name we give to the state, and the second is the function called once the state is started.

state.add(key, state) adds a new state. You must give each state a unique name in key argument by which you’ll identify it. state is usually a JavaScript object or a function.

In other words, we bind playGame function to a state called PlayGame.

And finally this is how a state is started.

state.start(key) starts the state previously named with key.

At this time, PlayGame state is started, calling playGame function which will consequently call playGame.create function.


Next Tutorial →

Creating tile graphics using a sprite sheet

← Previous Tutorial

Running your game