phaser3-docs
phaser3-docs copied to clipboard
Accessing body-parameters not working
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'.
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
...
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!
Same problem here, any solutions?
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);
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 😊