【问题标题】:Using variables from create in the update function Phaser 3在更新函数 Phaser 3 中使用 create 中的变量
【发布时间】:2022-09-29 14:12:54
【问题描述】:

在我的游戏中,我试图使用我在该范围之外的创建函数中启动的变量之一,并在更新函数中使用。理想情况下,我的代码如下所示:

create()
    {
       const map = this.make.tilemap({ key: \'mainmap\' })
       const tileset = map.addTilesetImage(\'Serene_Village_16x16\', \'tiles\', 16, 16, 1, 2)

       const Next1 = map.createLayer(\'Next\', tileset)

update(t: number, dt: number){       
        
    this.physics.world.collide(this.faune, Next1, ()=>{
        console.log(\"testing\")
        this.scene.stop(),
        this.scene.start(\'secondmap\');
        });

但是,问题在于我无法访问 next1 以与我的玩家角色 \"faune\" 发生碰撞,因为给出的错误是我 \"Cannot find name \'Next1\'.\"。如果有人知道如何通过 Phaser 跨功能使用它,那将非常有帮助。

谢谢,亚瑟

    标签: javascript typescript phaser-framework


    【解决方案1】:

    问题是您在 create 函数中定义函数 Next1 并尝试在 update 函数中访问它。
    您可以,只需在 create 函数中定义一个属性,如下所示:

    this.next1 = map.createLayer('Next', tileset)
    

    update 函数中,像这样使用它:

    this.physics.world.collide(this.faune, this.next1, () => { 
        // ...
    });
    

    为了避免编译器错误,在使用 typescript 时,您必须将属性添加到类定义中。

    class myScene extends Phaser.Scene {
        // you can use the exact datatype if you know it
        public next1:any; 
        ...
    }
    

    或者简单地将this.physics ... 代码放入create 函数中。

    【讨论】:

    • 我无法在 create 变量中使用 this.Next1,因为它在 Game 类型上不存在,并且尝试将其移到函数外部会导致更多错误,这些错误与 Phaser 内部相关,而不是我的整个代码。您关于将其移至 create 函数的观点不适用于我试图实现的目标,因为它需要更新并在整个过程中不断检查冲突。
    • this.next1 = ... 在 javascript 中创建此属性。由于您使用的是打字稿,因此您可以通过在 class ... extends Phaser.Scene { 行下添加行 public next1:any; 来简单地在类定义中定义 th 属性。比上面的代码应该编译。
    • @ctrl_cheeb_del 问题解决了吗?或者您还有其他问题吗?
    猜你喜欢
    • 2021-11-11
    • 2020-11-11
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 2020-01-27
    • 1970-01-01
    • 2017-09-11
    • 2015-07-23
    相关资源
    最近更新 更多