代码之家  ›  专栏  ›  技术社区  ›  yolenoyer

使用javascript ES6类添加Phaser sprite

  •  1
  • yolenoyer  · 技术社区  · 7 年前

    我使用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))

    以下是呈现的输出:

    Rendered output

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

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

    我错过了什么?

    2 回复  |  直到 7 年前
        1
  •  0
  •   yolenoyer    7 年前

    我可以通过改变 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() 方法:

    同时创造它的身体。 类,然后可以将它们传递给此方法 创建 .

        2
  •  0
  •   miggp    7 年前

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

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