简体   繁体   中英

Phaser some methods are missing on my Phaser.Physics.Arcade.Sprite

I'm trying to build a game with the Phaser 3 game engine. I'm using TypeScript and writing classes fro each of my entities.

I've started with some clouds in the background. I started to remove the arcade gravity and add the velocityX for the wind. My class looks like this

class Cloud extends Phaser.Physics.Arcade.Sprite {
    constructor(scene, x, y) {
        super(scene, x, y, 'cloud');
        this.setGravityY(0);
        return this;
    }

    static preload(scene) {
        scene.load.image('cloud', cloudAsset);
    }
}

But I get a type error

Uncaught TypeError: Cannot read property 'gravity' of null

This makes no sense to me because the method setGravityY is a extended, you can see it in the screenshot bellow.

在此处输入图片说明

So why is body undefined? I thought that extending Phaser.Physics.Arcade.Sprite is supposed to have a body. Like in the docs here

在此处输入图片说明

You are correct that the Arcade Sprite should have a body. But the scene's physics does not know about this game object yet. So you have to add it to the scene physics like this:

class Cloud extends Phaser.Physics.Arcade.Sprite {
    constructor(scene, x, y) {
        super(scene, x, y, 'cloud');
        scene.physics.add.existing(this); //here you add this existing sprite object to scene's physics 
        this.setGravityY(0);
        return this;
    }
}

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