Phaser + Typescript 在更新中丢失范围

Phaser + Typescript losing scope in update

我觉得我做错了什么,但是搜索与 Phaser + Typescript 相关的范围问题时我什么也没想到(虽然 JS 'this' / 范围上的吨 - 它似乎没有翻译得很好)。

我正在尝试设置一个 Phaser.Game 实例,根据我的理解,它需要一些回调(在我的例子中,预加载、创建然后更新)。在浏览器关闭之前调用更新。

我的问题是在更新中,我无法访问当前 class 中的变量。

代码:

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;
    }
}    

很确定它在这条线上:

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

您尚未将上下文与 this.update 相关联,因此当 Phaser 调用它时,它不会知道 this 应该是什么。

尝试做 update: () => this.update(),或 update: this.update.bind(this),甚至 update: function() { _this.update() }(其中 _this 是一个变量,它捕获了 this 之外的正确值函数),取决于你的 JS 版本。