cammil Posted March 27, 2015 Share Posted March 27, 2015 I have seen game states being constructed in a few different ways:// the game object is an argument of the constructor, and also property of the statevar state1 = function(game){ this.preload = function(){ this.game.load.image('img1', 'assets/img1.png'); ... } ...};// the state appears to be synonymous with the game objectvar state2 = function(){ this.preload = function(){ this.load.image('img1', 'assets/img1.png'); ... } ...};Both appear to work, though I don't understand why. Could someone enlighten me? Also, are there recommendations as to which one would be better? Or what are their relative pros and cons? (I might be able to answer this myself if I understood why both work!) Link to comment Share on other sites More sharing options...
JazzAceman Posted March 27, 2015 Share Posted March 27, 2015 It is unnecessary to have the game object as an argument of the constructor. You can use any empty object or function object as your implementation of a state object, no parameters required. JavaScript is a weak typed language so the state object is not forced to be any specific data type. Internally Phaser adds some properties of the game-object to your implementation of the state object, like the game object itself, the game's .add, .make, .camera properties and so on. Then it uses some standard-callback methods and links them with the corresponding methods on your own state object, if you implemented them. The Phaser.State object itself is only an example implementation you can inherit from, but since the nature of dynamic property appending in JavaScript, every object is suitable for being a valid state object. You only have to implement the necessary methods for initializing and running your game. And be careful, Phaser dosen't add every single property of the game obejct to your state. Although some tutorials say otherwise: The game object and your state object are never equivalent. So for short: The second version of your example-states is the better one. But it dosen't has to be a function at all, only if you want to perform some Phaser Framework independent object-initializations (constructor). If not, you can also use JSON object notation, or an empty object:var state3 = { preload: function() { ... }, create: function() { ... }, ...}var state4 = {};state4.preload = function() { ...} cammil 1 Link to comment Share on other sites More sharing options...
cammil Posted March 27, 2015 Author Share Posted March 27, 2015 This is an extremely clear and helpful answer. Many thanks. Link to comment Share on other sites More sharing options...
Recommended Posts