使用 javascript ES6 class 添加 Phaser 精灵

Adding a Phaser sprite using a javascript ES6 class

我有以下最小代码,使用 Phaser.js 3.11.0 和 Javascript ES6:

class Ship extends Phaser.Physics.Arcade.Image {
    constructor(scene, x, y) {
        super(scene, x, y, 'ship');
    }
}

class Scene extends Phaser.Scene {
    preload() {
        this.load.image('ship', require('../assets/ship.png'));
    }

    create() {
        this.ship1 = this.physics.add.existing(new Ship(this, 50, 70));
        this.ship2 = this.physics.add.image(150, 70, 'ship');
    }
}

new Phaser.Game({
    type: Phaser.AUTO,
    width: 200,
    height: 150,
    scene: Scene,
    physics: {
        default: 'arcade',
        arcade: {
            debug: true,
        },
    },
});

使用 this.physics.add.existing(new Ship(this, 50, 70)) 不起作用:即使显示了正确大小的调试边界框,也不显示精灵。

这是渲染后的输出:

如果我不使用物理,精灵会正确显示:

class Ship extends Phaser.GameObjects.Image {
    ...
}

class Scene extends Phaser.Scene {
    ...
    create() {
        this.ship1 = this.add.existing(new Ship(this, 50, 70));
        ...
    }
}

我错过了什么?

我能够通过更改 create() 方法解决问题:

create() {
    this.ship1 = this.add.existing(new Ship(this, 50, 70));
    this.physics.world.enable([ this.ship1 ]);
}

确实,您可以在API documentation中阅读有关Phaser.Physics.Arcade.World#enable()方法的内容:

Calling factory methods encapsulates the creation of a Game Object and the creation of its body at the same time. If you are creating custom classes then you can pass them to this method to have their bodies created.

为什么不在配置中调用 Arcade physics main.js?即:

const config = {
    type: Phaser.AUTO,
    width: window.innerWidth,
    height: window.innerHeight,
    physics: {
        default: 'arcade',
        arcade: {
            debug: true
        }
    },
    scene: [
        BootScene,
        LevelScene,
    ]
}