Episode 2: Methods, properties and function flow in state

Basically states are objects that consists one or more methods. Initially state has some methods and properties predefined. You can learn about them in this article.

Predefined methods are:

  • init
  • preload
  • loadUpdate
  • loadRender
  • create
  • update
  • preRender
  • render
  • resize
  • paused
  • resumed
  • pauseUpdate
  • shutdown

State without preload, create, update or render won’t even run. Other methods listed above are optional.

Predefined properties are:

Check full list of properties here.

These properties are in fact shortcuts. They cut down amount of chars needed to create game. For example, instead of using this.game.math.between(1, 10) you can simply write this.math.between(1, 10).

Order of functions triggering and their usage

  1. init – is triggered once after state start. When you’re starting a new state you can pass params to this method eg. this.state.start(‘StateName’, true, false, yourVar, yourVar2, yourVar3) and in your init function init: function(yourVar, yourVar2, yourVar3). This function is helpful to prepare some variables for your app. You can also add objects to the scene but graphics must be preloaded in previous state.
  2. preload – in this moment phaser loops through loadUpdate and loadRender until all elements are preloaded. You should limit preload usage to calling only load calls eg. this.load.image(‘bg’, ‘bg.jpg’).
    Preloading an audio file is special task. You should not only download audio to browser but decode it before using. Please check example from this episode.
  3. create – is fired just after init. This method is used to add elements to the scene. Everything from preloader is available at this moment. After this stage phaser is looping through update, preRender and render functions.
  4. shutdown – this function is fired just before switching to the next state. You can use it to free unneeded resources.

Source code for this lesson is here.

Additional information

You can use Chromes builtin throttling functionality to test your preloaders (press F12 and go to network tab).

Throttling in Chrome
Throttling in Chrome