简体   繁体   中英

phaser js undefined variable within loading function

I'm just starting out using phaser JS for game dev but have come across a an odd issue which I need some help on.

Let me show my code and explain where things are going wrong:

 class SimpleGame { game: Phaser.Game; csvTM: string; constructor (csvTM: string) { this.csvTM = csvTM; this.game = new Phaser.Game(800, 600, Phaser.AUTO, 'content', { preload: this.preload, create: this.create }); } test() { console.log("map test: " + this.csvTM); } preload() { console.log("map preload: " + this.csvTM); this.game.load.image('logo', 'empty_room.png'); this.game.load.tilemap("ItsTheMap", this.csvTM, null, Phaser.Tilemap.CSV); this.game.load.image("Tiles", "concrete.png"); } create() { console.log("map create: " + this.csvTM); var map = this.game.add.tilemap('ItsTheMap', 32, 32); map.addTilesetImage("Tiles"); var layer = map.createLayer(0); layer.resizeWorld(); } } 

Now what i'm trying to do here is simply pass a csv file path to the constructor of the SimpleGame object. When just using an absolute path, everything works just fine and i'l able to see the grid, etc. The issue comes in when I try to use the variable. Notice I have three log statements all displaying the contents of csvTM variable. Now what I do is first:

 var game = new SimpleGame(msg["Commands"][0][1]); game.test(); 

which loads the new phaser object and passes the file path into the constructor. Now im 100% sure the local variable csvTM is set becuase when I do teh game.test() above I see the file path. However in preload and create the csvTM is always undefined.. thus breaking my code. I do notice that the game object which is also made in the constructor seems to work and is always defined.

Does anyone know why my local variable string is undefined in only preload and create while the game local variable seems to be defined?

Thanks for your help!

It is hard for me to be sure about this since I do not have access to all of your code. But I think it might be a case of the classic javascript "this" problem.

Try defining the methods as:

preload = () =>  { ... }
create = () =>  { ... }

This will make sure that "this" inside the functions is actually the correct "version" of "this".

There are many questions (and answers) about how "this" works in typescript/javascript on stackoverflow but my answer to a previous similar question might explain why you are getting this behaviour: Visual Studio shows wrong value for `this` in TypeScript

EDIT:

As Marwane KA pointed out in his comment to my answer the issue can be solved by replacing

{ preload: this.preload, create: this.create }

in the initiation with "this".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM