Phaser + Typescript losing scope in update

a 夏天 提交于 2019-12-24 11:12:43

问题


I feel like I'm doing something wrong, but searching for Phaser + Typescript related scope issues I'm coming up with nothing (tons on JS 'this' / scope though - it doesn't seem to translate well).

I'm trying to set up a Phaser.Game instance, which from my understanding takes a few callbacks (in my case, preload, create then update). Update gets called until the browser is closed.

My issue is that inside update, I have no access to the variables inside the current class.

Code:

import { Player } from "./Player";
import { InputManager } from "./input/InputManager";
import { Point } from "./geometry/Point";

export class Game {
    private player: Player;
    private inputManager: InputManager;
    private game: Phaser.Game;

    constructor() {
        this.player = new Player();
        this.inputManager = new InputManager(new Phaser.Keyboard(this.game));
        this.game = new Phaser.Game(1024,400, Phaser.AUTO, 'content', { preload: this.preload, create: this.create, update: this.update });
    }

    private preload(): void {
        console.log(this.inputManager); // undefined
        this.game.load.image('terminal', 'terminal.png');
    }

    private create(): void {
        console.log("create");
        console.log(this.inputManager); // undefined
        var logo = this.game.add.sprite(this.game.world.centerX, this.game.world.centerY, 'terminal');
        logo.anchor.setTo(0.5, 0.5);

    }

    private update(): void {
         // update gets called right away, so check for inputManager to be initialized before contuing
        if(!this.inputManager) { // Will always be false - "this" isn't what i'm expecting
            console.log("undefined iputManager");
            return;
        }

        console.log("initialized update");
        this.inputManager.update();
        if(this.inputManager.newDirection)
        {
            this.move(this.inputManager.newDirection);
            this.inputManager.Clear();
        }
    }

    private move(newDirection: Point): void {
        // TODO: Movement check for the player
        this.player.Location.X += newDirection.X;
        this.player.Location.Y += newDirection.Y;
    }
}    

回答1:


Pretty sure it's on this line:

this.game = new Phaser.Game(1024,400, Phaser.AUTO, 'content', { preload: this.preload, create: this.create, update: this.update });

You haven't associated a context with this.update, so when Phaser calls it, it won't know what this should be.

Try doing update: () => this.update(), or update: this.update.bind(this), or even update: function() { _this.update() } (where _this is a variable that captured the correct value of this outside of the function), depending on your version of JS.



来源:https://stackoverflow.com/questions/45991649/phaser-typescript-losing-scope-in-update

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