Phaser + Typescript在更新中丢失范围

时间:2017-09-01 00:01:36

标签: typescript phaser-framework

我觉得我做错了什么,但是搜索Phaser + Typescript相关的范围问题我没有提出任何问题(很多关于JS'这个' /范围虽然 - 它似乎没有很好的翻译。)

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

我的问题是内部更新,我无法访问当前类中的变量。

代码:

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 个答案:

答案 0 :(得分:1)

非常肯定它就在这一行:

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版本。