【问题标题】:phaser js undefined variable within loading function加载函数中的phaser js未定义变量
【发布时间】:2015-07-23 05:20:23
【问题描述】:

我刚开始使用 Phaser JS 进行游戏开发,但遇到了一个奇怪的问题,我需要一些帮助。

让我展示我的代码并解释哪里出了问题:

class SimpleGame {
    game: Phaser.Game;
    csvTM: string;
    
    constructor (csvTM: string) {

        this.csvTM = csvTM;

        this.game = new Phaser.Game(800, 600, Phaser.AUTO, 'content', { preload: this.preload, create: this.create });
    }

    test() {
        console.log("map test: " + this.csvTM);
    }

    preload() {
        console.log("map preload: " + this.csvTM);
        this.game.load.image('logo', 'empty_room.png');
        this.game.load.tilemap("ItsTheMap", this.csvTM, null, Phaser.Tilemap.CSV);
        this.game.load.image("Tiles", "concrete.png");
    }

    create() {
        console.log("map create: " + this.csvTM);
        var map = this.game.add.tilemap('ItsTheMap', 32, 32);
        map.addTilesetImage("Tiles");
        var layer = map.createLayer(0);
        layer.resizeWorld();

    }

}

现在我在这里要做的只是将一个 csv 文件路径传递给 SimpleGame 对象的构造函数。仅使用绝对路径时,一切正常,我可以看到网格等。当我尝试使用变量时,问题就出现了。请注意,我有三个日志语句都显示 csvTM 变量的内容。现在我要做的是首先:

var game = new SimpleGame(msg["Commands"][0][1]);
            game.test();

加载新的移相器对象并将文件路径传递给构造函数。现在我 100% 确定设置了局部变量 csvTM,因为当我执行上面的 game.test() 时,我看到了文件路径。然而,在预加载和创建 csvTM 时始终未定义.. 从而破坏了我的代码。我确实注意到在构造函数中创建的游戏对象似乎可以工作并且总是被定义。

有谁知道为什么我的局部变量字符串只在预加载和创建中未定义,而游戏局部变量似乎已定义?

感谢您的帮助!

【问题讨论】:

    标签: javascript typescript phaser-framework


    【解决方案1】:

    我很难确定这一点,因为我无法访问您的所有代码。但我认为这可能是经典 javascript“this”问题的一个案例。

    尝试将方法定义为:

    preload = () =>  { ... }
    create = () =>  { ... }
    

    这将确保函数中的“this”实际上是“this”的正确“版本”。

    关于“this”如何在 stackoverflow 上的 typescript/javascript 中工作有很多问题(和答案),但我对之前类似问题的回答可能会解释为什么你会出现这种行为:Visual Studio shows wrong value for `this` in TypeScript

    编辑:

    作为 Marwane K.A.在他对我的回答的评论中指出,这个问题可以通过替换来解决

    { preload: this.preload, create: this.create }
    

    以“this”开头。

    【讨论】:

    • 同意诊断,但我认为可以通过在游戏初始化中将{ preload: this.preload, create: this.create } 替换为this 来解决。
    • 我没有注意到!谢谢,更新了答案以反映这一点。
    • 我不太明白?预加载和创建基本上是映射到函数地址/值的哈希键。如果我只用“this”替换整个映射,它只是对具有预加载和创建函数的类的引用,而不是哈希?
    • 我不熟悉 ES6 类,但 AFAIK 传递 \{ preload: this.preload, create: this.create }` 和 this 之间没有区别,除了我们的问题重新讨论。两者基本上都只是 javascript 对象,其属性 preload & create 映射到函数。 (编辑:嗯,实际上还有其他差异,但总而言之,Phaser 不应该注意到任何事情)
    • 区别(至少我们在这里关心的那个)是this。如果您在函数内部传递一个新对象(带有{ ... }this 将是那个新对象,而不是来自SimpleGame 实例的this
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-13
    • 2023-01-26
    相关资源
    最近更新 更多