I was helping someone in the Phaser Game Makers Facebook group a couple of weeks ago when the issue of states came up.<\/p>\n
In most technical\u00a0of terms, a state is a class. The Phaser documentation describes it as follows:<\/p>\n
This is a base State class which can be extended if you are creating your own game. It provides quick access to common functions such as the camera, cache, input, match, sound and more.<\/p><\/blockquote>\n
This is great because it sets up things like the preload, create and update functions. \u00a0In the most basic sense, with a few exceptions, I like to think of the states as screens.<\/p>\n
My basic games will usually include<\/p>\n
\n
- Title State-nice graphic with a play button<\/li>\n
- Main State-where the game lives<\/li>\n
- Over State-game over screen with a play again button<\/li>\n<\/ul>\n
You can see why it is easy to think of states as screens. One of the nice things about states is you can simply restart them. That means to replay the game I simply start the main state from the over state.<\/p>\n
Here is a basic state<\/p>\n
var StateMain={ \r\n \r\n preload:function()\r\n {\r\n \r\n },\r\n \r\n create:function()\r\n {\r\n \r\n },\r\n \r\n update:function()\r\n { \r\n \r\n } \r\n \r\n}<\/pre>\nTo add a state to the game we use<\/p>\n
game.state.add(\"StateMain\",StateMain);<\/pre>\nTo start a state use:<\/p>\n
game.state.start(\"StateMain\");<\/pre>\nI normally use these in a file called main.js<\/p>\n
var game;\r\nwindow.onload = function()\r\n{\r\n game=new Phaser.Game(480,640,Phaser.AUTO,\"ph_game\");\r\n\t\r\n game.state.add(\"StateMain\",StateMain);\r\n game.state.start(\"StateMain\");\r\n}<\/pre>\nHere is a quick example of switching between 3 states.<\/p>\n
Just click to change states.<\/p>\n\n\n