【问题标题】:Phaser + Typescript losing scope in updatePhaser + Typescript 在更新中失去范围
【发布时间】:2018-02-10 00:16:58
【问题描述】:

我觉得我做错了什么,但是在搜索 Phaser + Typescript 相关的范围问题时我一无所获(尽管 JS 'this' / scope 上的大量内容 - 它似乎翻译得不好)。

我正在尝试设置 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;
    }
}    

【问题讨论】:

    标签: typescript phaser-framework


    【解决方案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 版本。

    【讨论】:

    • @Matt 您可能会遇到与 this.create 相同的问题,请注意!
    猜你喜欢
    • 2017-09-11
    • 2014-05-08
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-07
    相关资源
    最近更新 更多