Kokodoko
Kokodoko

Reputation: 28128

How add physics to Phaser 3 sprite?

I am trying to implement the Phaser 3 documentation for physics sprites in a typescript project, but this seems less straightforward than expected:

NOT WORKING

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);
    }
}

But when creating a new BMO() the sprite has no physics. The physics engine itself is working because I can pass an image and it works:

WORKING

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);
  }
}

FIX?

So perhaps the sprite still needs to be added to the physics engine manually (even though it's a physics sprite), but it's not possible to pass the whole sprite as an argument:

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

How do I create a Phaser.Physics.Arcade.Sprite instance?

Upvotes: 4

Views: 5641

Answers (3)

lsiu
lsiu

Reputation: 2355

I think you just need to add scene.physics.add.existing(this); to your class

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);
    }
}

Upvotes: 3

juanitogan
juanitogan

Reputation: 1858

I just ran into the same question. I found the answer here:

https://rexrainbow.github.io/phaser3-rex-notes/docs/site/arcade-body/

In short:

scene.physics.add.existing(gameObject, isStatic)

I haven't checked yet which types of GameObjects can be added or extended this way but I'm guessing any of them can, and not just Physics.*.*.

Upvotes: 1

You should include a physics section into Phaser.Game config.

Upvotes: 1

Related Questions