blackhawx Posted September 12, 2018 Share Posted September 12, 2018 I'm getting back into researching / learning Phaser 3 and how scenes operate. Today I have learned that if we place the 'this' keyword ' in front of a label, it allows us to reference data across the create() and update() methods. For example.... gameScene.create = function() { this.enemy1 = this.add.sprite(250, 180, 'enemy'); } gameScene.update = function() { if (this.enemy1.scaleX <= 2) { this.enemy1.scaleX += 0.01; this.enemy1.scaleY += 0.01; } } With that code, I can see my enemy slowly increasing in size until he reaches twice his size. But from a coding perspective is there an alternative approach to sharing enemy1 across various methods, rather than using 'this' in front it everywhere? I'm going have a lot of labels created and loaded through out various scenes, and would love to know if there is a cleaner name spacing convention that can be taken. I would love to remove the 'this' keyword completely, and get back into using 'let' or 'var'. But I don't see any way of doing such, especially if I want to share data across methods... Thanks! Link to comment Share on other sites More sharing options...
rich Posted September 12, 2018 Share Posted September 12, 2018 This is nothing to do with Phaser, and everything to do with how JS works I'm afraid. It's standard JS scoping. I'd recommend an ES6 crash course or similar, just to get up to speed, as it will help tremendously the further into your game you get. Link to comment Share on other sites More sharing options...
blackhawx Posted September 13, 2018 Author Share Posted September 13, 2018 Thank you so much rich for the feedback. I apologize if my original concern is slightly unclear. What I would like to know is why we can't we do something like the following, to cut down on typing the keyword 'this' every time... /* my original code */ this.enemy1.scaleX = 1; //another way of scaling! this.enemy1.scaleY = 1; //another way of scaling! /* can we do something like this in Phaser 3 so that properties are stored under a single this keyword? I've tested this short example but it breaks on me. Can I tweak it to get it working? */ this.enemy1 = { scaleX : 1, scaleY : 1 } Is this not acceptable in Phaser 3? Many thanks! Link to comment Share on other sites More sharing options...
rich Posted September 13, 2018 Share Posted September 13, 2018 I'm failing to see how you've saved any coding there. All it's done is move a property from one object to another. If you want to reference enemy1 elsewhere in your code, you'll still need to use 'this.enemy1'. It's just standard JS. Link to comment Share on other sites More sharing options...
blackhawx Posted September 13, 2018 Author Share Posted September 13, 2018 Understood, thanks for clearing things up! Link to comment Share on other sites More sharing options...
Recommended Posts