简体   繁体   中英

Adding a Phaser sprite using a javascript ES6 class

I have the following minimal code, using Phaser.js 3.11.0 and 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,
        },
    },
});

Using this.physics.add.existing(new Ship(this, 50, 70)) doesn't work: the sprite is not displayed, even if the debug bounding box is shown, with the right size.

Here is the rendered output:

渲染输出

If I don't use physics, the sprite displays correctly:

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

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

What am I missing?

I was able to fix the problem by changing the create() method:

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

Indeed, you can read in the API documentation , about the Phaser.Physics.Arcade.World#enable() method:

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 .

Why don't you call the Arcade physics in the config main.js?ie:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM