Jump to content

create() can't access other class variables?


coolwhip
 Share

Recommended Posts

 

Say I have a simple class:

class SimpleGame {

    game: Phaser.Game;
    myColor: Phaser.Color;
    constructor() {
        this.myColor = Phaser.Color.createColor(255,255,0);
        this.game = new Phaser.Game(1200, 600, Phaser.AUTO, 'content', { preload: this.preload, create: this.create});
        
}

    preload(){
        this.game.load.image("platform", "Graphics/platform.png");
    }
    create() {
        console.log(this.myColor);
    }
}

window.onload = () => {
    var game = new SimpleGame();
};

The console always prints/returns undefined and if I try to modify the value of myColor, it brings up an error.

Can the create method not access class properties? What have I done wrong here?

Thanks

Link to comment
Share on other sites

It's because you're passing the methods in an object,  in such cases these methods will always refer to it's parent object. Which in this case is Phaser.Game.

And this.MyColor variable doesn't exist there. 

let preload = function(){
	console.log( this ) //// points to Phaser.Game
}
var game = new Phaser.Game(1200, 600, Phaser.AUTO, 'content', { preload: preload })

I'd recommend using ES6 way of extending Phaser classes , it's less confusing IMHO.

class BootState extends Phaser.State {
	init(){
		this.myColor = Phaser.Color.createColor(255,255,0);
	}
	preload(){
        this.game.load.image("platform", "star.png");
    }
    create() {
        console.log(this.myColor);
    }
}

class SimpleGame extends Phaser.Game {
    constructor() {
		super(1200, 600, Phaser.AUTO, 'content' );
   }
	init(){
		 this.state.add("boot", BootState );
		 this.state.start('boot');
	}
}

window.onload = () => {
    var game = new SimpleGame().init();
};

 

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...