如何在 Phaser 3 精灵中添加物理引擎?

4
我正在尝试在TypeScript项目中实现Phaser 3物理精灵文档,但这似乎没有想象中那么简单:

不起作用

export class BMO extends Phaser.Physics.Arcade.Sprite {

    constructor(scene) {
        super(scene, 100,150, "bmo")
        this.scene.add.existing(this)
    }

    create(){
        this.setVelocity(100, 200);
        this.setBounce(1, 1);
        this.setCollideWorldBounds(true);
    }
}

但是当创建一个new BMO()时,精灵没有物理效果。 物理引擎本身是在工作的,因为我可以传递一张图片并且它有效:

有效

export class GameScene extends Phaser.Scene {

  create(){
    let logo = this.physics.add.image(400, 100, 'bmosmall')
    logo.setVelocity(100, 200);
    logo.setBounce(1, 1);
    logo.setCollideWorldBounds(true);
  }
}

修复?

因此,即使它是物理精灵,也可能仍需要手动将精灵添加到物理引擎中,但无法将整个精灵作为参数传递:

 export class BMO extends Phaser.Physics.Arcade.Sprite {
     create(){
        this.scene.physics.add.sprite(this)
     }
 }

我该如何创建一个 Phaser.Physics.Arcade.Sprite 实例?
3个回答

2

我认为你只需要在你的类中添加 scene.physics.add.existing(this);

export class BMO extends Phaser.Physics.Arcade.Sprite {

    constructor(scene) {
        super(scene, 100,150, "bmo")
        scene.physics.add.existing(this); // add this line
        this.scene.add.existing(this)
    }

    create(){
        this.setVelocity(100, 200);
        this.setBounce(1, 1);
        this.setCollideWorldBounds(true);
    }
}

1
你应该在Phaser.Game配置中包含一个物理学部分。

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接