Collisions problem when adding an "extended" Sprite

Hi everyone !!
I am really new to Phaser and this is my first topic here.

I’ve been doing the “starter project” available at the official Phaser 3 website : https://phaser.io/tutorials/making-your-first-phaser-3-game

Everything is working fine with the tutorial’s setup. But I tried to refactor the player sprite in a different class.

So I changed this :

this.player = this.physics.add.sprite(100, 450, "dude");

To :

this.player = new Player({
    key: 'player',
    x: 100,
    y: 450,
    scene: this
});

The Player class extend Phaser.GameObjects.Sprite and in the constructor I added this :

this.scene.physics.world.enable(this);
this.body.setCollideWorldBounds(true);
this.scene.add.existing(this);

In the two setups, I’m doing this:

this.physics.add.collider(this.player, this.platforms);

But here is the problem ! When I add a Player this way, the collider don’t look to make it’s job, at least not the way intended:
Capture%20d%E2%80%99%C3%A9cran%20de%202018-12-13%2022-49-32

But when I get back to the previous setup, everything is working fine again.
Capture%20d%E2%80%99%C3%A9cran%20de%202018-12-13%2023-32-19

Do you guys have an idea of what’s going on ? Did I missed something ?

Thanks in advance

What’s the entire constructor function?

Here is what my constructor look like :

constructor(params: any) {
    super(params.scene, params.x, params.y, params.key);

    this.initInput();
    this.initEntity();
    this.initAnimations();
}

And the initEntity() :

initEntity() {
    this.scene.physics.world.enable(this);
    this.body.setCollideWorldBounds(true);
    this.scene.add.existing(this);
}

I saw other class like this that was doing all the initEntity things on params.scene instead of this.scene but the result is the same for me.

PS: I’m using Typescript

Is there a texture key named ‘player’?

There is no texture key named player, but instead the “texture” you can see is add with an animation added in the Player class update method which is called by the scene’s update method.

Here is how it look like :

initAnimations() {
    // ...
    this.scene.anims.create({
      key: 'turn',
      frames: [{ key: 'dude', frame: 4 }],
      frameRate: 20
    });
}

update() {
    // ...
    this.anims.play('turn');
}

And in the Scene class:

update() {
    this.player.update();
}

I updated the post to show the “working way” with this.physics.add.sprite directly in the Scene class.

I think the easiest solution is to pass the key ‘dude’ instead.

The body likely has the wrong size because it’s created before the sprite has the texture assigned.

Ok that was it !
I was thinking that the size was updated when the texture was set to the Sprite.

I’m closing this topic, many thanks @samme !

I think you can also do

player.body.setSize(); // no args

after it has received a texture, if you prefer.

Will try it later to create a generic Enemy class