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:
State without preload, create, update or render won’t even run. Other methods listed above are optional.
Predefined properties are:
- game – Phaser.Game instance
- add – Phaser.GameObjectFactory
- make – Phaser.GameObjectCreator
- camera – Phaser.Camera
- cache – Phaser.Cache
- input – Phaser.Input
- load – Phaser.Loader
- math – Phaser.Math
- sound – Phaser.SoundManager
- scale – Phaser.ScaleManager
- state – Phaser.StateManager
- stage – Phaser.Stage
- time – Phaser.Time
- tweens Phaser.TweenManager
- world – Phaser.World
- particles – Phaser.Particles
- rnd – Phaser.RandomDataGenerator
- physics – Phaser.Physics
- key – The string based state key
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
- 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.
- 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.
- 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.
- 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.
You can use Chromes builtin throttling functionality to test your preloaders (press F12 and go to network tab).