elitian Posted April 9, 2016 Share Posted April 9, 2016 I built a simple game using phaser, but didn't use multiple game states. The game had only one screen and no states! It was all poorly done. So now I'm learning game states. In this code snippet, taken from a phaser game https://github.com/alexdantas/ludum-dare-29/blob/master/js/states/play.js, we have, for example, a line consisting of this.game.camera.setBoundsToWorld(). I know how this works, but i'm having trouble knowing who is this here. I know this in OOP refers to the "owner" of the function, but in this case, who is it? Another doubt I'm struggling with is, where does the .game.camera.setBoundsToWorld() comes from? Is it from when Phaser initializes a new state? When it start a new state, does it create a new "main state", which in this case is what the "this" refers to, and add attributes/methods to it? Like this game.camera.setBoundsToWorld() method? function Play() {} Play.prototype = { create: function() { this.game.physics.startSystem(Phaser.Physics.ARCADE); this.game.stage.backgroundColor = '#000'; // initialize game variables this.cash = 0; this.chunkGroup = this.game.add.group(); this.nextChunkY = 0; this.game.world.bounds.x = 0; this.game.world.bounds.height = 1024; this.game.camera.setBoundsToWorld(); this.lastChunkIndex = 0; this.tephra = this.game.add.group(); this.rocks = this.game.add.group(); this.gems = this.game.add.group(); this.carrots = this.game.add.group(); this.lastChunk = null; this.chunkIndex = 0; this.generateChunk(); this.generateChunk(); }, } Link to comment Share on other sites More sharing options...
Arcanorum Posted April 10, 2016 Share Posted April 10, 2016 If you want to see what 'this' is actually referring to at a particular point, just do 'console.log(this);'. In your code, the Play state is the "owner" of the create function, so 'this' refers to the currently running state. Each state has a property 'game', which is a reference to the Phaser game object. In general, you should be trying to add things to the state itself, rather than to the game object. I would recommend removing the '.game' from 'this.game.physics.startSystem(Phaser.Physics.ARCADE);', so that the physics system is started for this state only. Every time you are doing 'this.game.add.group()' is also adding those groups to the game object, not to the state. drhayes and elitian 2 Link to comment Share on other sites More sharing options...
elitian Posted April 10, 2016 Author Share Posted April 10, 2016 Nice, thanks a lot! Now all is clear Link to comment Share on other sites More sharing options...
Recommended Posts