coolwhip

create() can't access other class variables?

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

Share this post


Link to post
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();
};

 

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

  • Recently Browsing   0 members

    No registered users viewing this page.