Phaser: this.game is undefined in the Update function

淺唱寂寞╮ 提交于 2020-01-16 18:17:41

问题


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;



来源:https://stackoverflow.com/questions/30359415/phaser-this-game-is-undefined-in-the-update-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!