Currently, I've been immersed in the world of game development with Phaser 3 by following this insightful tutorial at . However, my focus has now shifted towards deploying these games online and adapting the code for use with TypeScript while gearing up to integrate it into an Ionic 5 app. In the tutorial, a crucial part involves setting the velocity of a player sprite. To accomplish this, two essential classes need to be created: Entities.js
(renamed as entities.ts
) and Player.js
(transformed into player.ts
). These entities are designed to extend Phaser.GameObjects.Sprite
, with the player being an entity that extends the entities class. Although everything is progressing smoothly, an issue arises when attempting to set the player's velocity.
The first file 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);
}
}
Next, we have 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);
}
}
Upon introducing the line this.body.setVelocity(0, 0)
, an error surfaces:
Property 'setVelocity' does not exist on type 'Body | StaticBody | BodyType'. Property 'setVelocity' does not exist on type 'StaticBody'
. It appears that the sprite's body can be classified as either a Body
, StaticBody
, or BodyType
object. The documentation reveals that the Body
class supports the function setVelocity</code, whereas the <code>StaticBody
class lacks this ability.
Could it be that TypeScript expects all types within the union to support the function? If so, is there a way to specify the specific body type being used in function calls? Despite multiple attempts, parsing doesn't seem to yield any solutions.
In contemplating whether transitioning to developing in plain JavaScript for Ionic may alleviate the issue, I stumbled upon resources like . Nevertheless, before considering such a change, is there a method to explicitly define the desired type from the union for my function calls? Your insights would be greatly appreciated. Thank you for your assistance.