phaser3-docs icon indicating copy to clipboard operation
phaser3-docs copied to clipboard

Accessing body-parameters not working

Open digitsensitive opened this issue 6 years ago • 5 comments

Currently the console throws errors when I access body parameters in a Phaser.GameObjects.Sprite Class, although I have added it to the physics world.

Example:

export class Pipe extends Phaser.GameObjects.Sprite {
  constructor(params) {
    super(params.scene, params.x, params.y, params.key, params.frame);

    params.scene.physics.world.enable(this);
    this.body.setSize(20, 20);

    params.scene.add.existing(this);
  }
}

Error:

ERROR in ***/pipe.ts
.***/pipe.ts
[tsl] ERROR in /***/pipe.ts(20,15)
      TS2339: Property 'setSize' does not exist on type 'object'.

digitsensitive avatar Apr 21 '18 10:04 digitsensitive

I've got the same here. It seems that this.body is typed as object (in phaser.d.ts the body has this signature: object | Phaser.Physics.Arcade.Body | Phaser.Physics.Impact.Body) and not as Phaser.Physics.Arcade.Body after .enable() call, since I set Arcade Physics globally in the GameConfig. I don't know if it's a type design problem or something related to the typing techniques.

Anyway, I've solved explicitly typing body as a class property with the type it's supposed to be.

export class YourCoolObject extends Phaser.GameObjects.Graphics {
  body!: Phaser.Physics.Arcade.Body
  ...

raphaklaus avatar Jul 30 '18 18:07 raphaklaus

I have updated phaser to the newest version (3.18.1) and I am kind of still struggling with this problem. I could solve it with your approach @raphaklaus using body!: Phaser.Physics.Arcade.Body or request a change in the typescript definition file by simply assigning any as the signature of body. But somehow both of the solutions are not satisfying.

How are you guys approaching this problem? What is your work around? Any ideas on how to edit the TS Defs here? Thanks!

digitsensitive avatar Jun 30 '19 15:06 digitsensitive

Same problem here, any solutions?

Digitalheck avatar Sep 18 '19 19:09 Digitalheck

I just always separate the body as a variable, casting the type in it:

const body = this.body as Phaser.Physics.Arcade.Body;
body.setSize(20, 20);

dimoreira avatar Jan 17 '20 03:01 dimoreira

If you write code with Class you can fix this problem like so:

class Asteroid extends Phaser.GameObjects.Sprite {
    body: Phaser.Physics.Arcade.Body;
    
    constructor(scene, x = 0, y = 0, key = '') {
        super(scene, x, y, key);

        scene.physics.world.enableBody(this);

        this.body.allowGravity = false;

        scene.add.existing(this);
    }
}

Works for me 😊

KrzysiekF avatar Jan 17 '20 13:01 KrzysiekF