Phaser: this.game is undefined in the Update funct

2019-09-07 07:54发布

问题:

Good evening, sorry for asking again, but I need to be done with this by tomorrow for school. Basically, when I try to access the this.game variable in the update function, it says that it is undefined, to be specific, I get this; "Uncaught TypeError: Cannot read property 'state' of undefined". In my update function I have this:

create: function() {
    [...]
    map.setCollisionByExclusion([], true, doorLayer);
    [...]
}

When I try to access this.game in the update function on the collision action, I get the error mentioned above. Here's the code;

update: function() {
    [...]
    this.game.physics.arcade.collide(player, doorLayer, function() {
        if (hasItem) {
            this.game.state.start('Hallway'); //This is where I get the error
        }
    });
    [...]
}

Thank you for your time.

回答1:

this.game.physics.arcade.collide(player, doorLayer, function() { if (hasItem) { this.game.state.start('Hallway'); //This is where I get the error } });

Notice the inner this refers to the anonymous function you are passing which clearly does not have a member named game.

Ideally, rename this to something else and then use it. Now you can use myself variable inside the anonymous function passed and access myself's properties.

i.e.

var myself = this;