Faizy Posted May 6, 2017 Share Posted May 6, 2017 Hey, I know what the word *this* does. However I dont know why so many tutorials use 'this' instead of 'game'(or whatever your objectname is called...let´s just assume it´s called 'game'). See this for example. // Variable to store the arrow key pressed this.cursor = game.input.keyboard.createCursorKeys(); // Create the player in the middle of the game this.player = game.add.sprite(70, 100, 'player'); // Add gravity to make it fall this.player.body.gravity.y = 600; Instead of creating 'var player' he(the guy who wrote this tutorial) creates properties of the object 'game'. Is there any benefit to doing it like so? Or is it just because it´s OOP? Link to comment Share on other sites More sharing options...
Abhishek Singhal Posted May 8, 2017 Share Posted May 8, 2017 calling "game.add.sprite" is Phaser way of creating a sprite object with provided key and at the specified coordinates (x:70, y:100 & key: 'player') in this case. Above function call creates the sprite object and adds it to the game stage so that it is added to the view. But to keep a reference of the generated and added sprite within the script we store it to a variable " this.player ". Now, we can reference this.player anywhere in our script within the scope. Link to comment Share on other sites More sharing options...
samme Posted May 8, 2017 Share Posted May 8, 2017 Within the state callbacks (init/preload/create/update/render), this is actually the current state, not the game (but they have many properties in common). The game can always be found in this.game. Abhishek Singhal 1 Link to comment Share on other sites More sharing options...
Recommended Posts