I have been following this tutorial, https://learn.yorkcs.com/2019/02/07/build-a-space-shooter-with-phaser-3-3/ , to make games with Phaser 3 but since I want to deploy them online I'm converting the code to use with TypeScript as I am preparing it via an Ionic 5 app. In the tutorial, I'm supposed to set a player sprite's velocity. For clarity, there are two classes I must create, Entities.js (which I created as entities.ts) and Player.js (which I made into player.ts). The entities are supposed to be an extension of Phaser.GameObjects.Sprite, and the player is supposed to be an entity, extending the entities class. So far, I get everything working except when reaching the part about setting the player's velocity.
This is my entities.ts:
class Entity extends Phaser.GameObjects.Sprite {
constructor(scene, x, y, key, type) {
super(scene, x, y, key);
this.scene = scene;
this.scene.add.existing(this);
this.scene.physics.world.enableBody(this, 0);
this.setData('type', type);
this.setData('isDead', false);
}
}
And this is my player.ts:
class Player extends Entity {
constructor(scene, x, y, key) {
super(scene, x, y, key, 'Player');
this.setData('speed', 200);
this.play('sprPlayer');
}
moveUp() {
this.body.velocity.y = -this.getData('speed');
}
moveDown() {
this.body.velocity.y = this.getData('speed');
}
moveLeft() {
this.body.velocity.x = -this.getData('speed');
}
moveRight() {
this.body.velocity.x = this.getData('speed');
}
update() {
this.body.setVelocity(0, 0);
}
}
Once I write the line, this.body.setVelocity(0, 0), I get an error: Property 'setVelocity' does not exist on type 'Body | StaticBody | BodyType'. Property 'setVelocity' does not exist on type 'StaticBody'. Apparently the body of a sprite can be used for either a Body, StaticBody, or BodyType object. Checking on the documentation, the Body class https://photonstorm.github.io/phaser3-docs/Phaser.Physics.Arcade.Body.html allows for the setVelocity function to happen, whereas the StaticBody one https://photonstorm.github.io/phaser3-docs/Phaser.Physics.Arcade.StaticBody.html doesn't.
Is it that TypeScript expects for each of the possible types to support the function to be used? If so, is there a way for me to specify what type of body I'm using? I tried parsing to no avail.
Now, I think there may be a way to specify Ionic I wish to develop in plain JavaScript https://uptoskill.com/ionic-react-javascript/ , but without resorting to that, is there a way to specify which type from the union I wish to use in my function calls? Please let me know, and thanks for the help.