Zaelyth
December 13, 2018, 10:07pm
1
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:
But when I get back to the previous setup, everything is working fine again.
Do you guys have an idea of what’s going on ? Did I missed something ?
Thanks in advance
samme
December 13, 2018, 10:13pm
2
What’s the entire constructor function?
Zaelyth
December 13, 2018, 10:16pm
3
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
samme
December 13, 2018, 10:22pm
4
Is there a texture key named ‘player’?
Zaelyth
December 13, 2018, 10:30pm
5
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.
samme
December 13, 2018, 10:40pm
6
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.
Zaelyth
December 13, 2018, 10:47pm
7
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 !
samme
December 13, 2018, 10:54pm
8
I think you can also do
player.body.setSize(); // no args
after it has received a texture, if you prefer.
Zaelyth
December 13, 2018, 11:01pm
9
Will try it later to create a generic Enemy
class