使用 TypeScript 的 Phaser 上的联合类型不存在属性

用 Phaser 3 制作游戏,但因为我想要为了在线部署它们,我正在转换代码以与 TypeScript 一起使用,因为我正在通过 Ionic 5 应用程序准备它。在教程中,我应该设置玩家精灵的速度。为了清楚起见,我必须创建两个类,Entities.js(我将其创建为entities.ts)和Player.js(我将其制作为player.ts)。实体应该是 的扩展Phaser.GameObjects.Sprite,而玩家应该是一个实体,扩展了实体类。到目前为止,除了到达有关设置玩家速度的部分外,我一切正常。

这是我的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);

  }

}

这是我的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);

  }

}

一旦我写了行,this.body.setVelocity(0, 0),我得到一个错误:Property 'setVelocity' does not exist on type 'Body | StaticBody | BodyType'. Property 'setVelocity' does not exist on type 'StaticBody'。显然,精灵的主体可以用于BodyStaticBodyBodyType对象。检查文档,类Bodyhttps://photonstorm.github.io/phaser3-docs/Phaser.Physics.Arcade.Body.html允许该setVelocity功能发生,而StaticBodyhttps://photonstorm.github.io/ Phaser3-docs/Phaser.Physics.Arcade.StaticBody.html没有。

TypeScript 是否期望每种可能的类型都支持要使用的函数?body如果是这样,有没有办法让我指定我正在使用什么类型?我尝试解析无济于事。


至尊宝的传说
浏览 118回答 2
2回答

精慕HU

错误消息表明您的玩家主体是这些类型之一'Body | StaticBody | BodyType',但 StaticBody 没有setVelocity方法。Typescript 具有类型保护的概念来处理这种情况,您可以在其中使用具有不同成员的联合类型。这里的解决方案是检查 this.body 是否有 setVolicity 函数。update() {    // when true typescript know it is not a StaticBody    if ("setVelocity" in this.body)    this.body.setVelocity(0, 0);  }您还可以定义自定义类型保护函数并在 if 语句中使用它,如下所示://custom typeguard function with the return type 'body is Body'    function isBody(body: Body | StaticBody): body is Body {  return (body as Body).setVelocity !== undefined;}if (isBody(this.body)) {  this.body.setVelocity(5); }

慕姐4208626

正如 jcalz 所解释的,答案是测试相关对象是否是包含要调用的函数的类的实例。换句话说,确保我们希望使用Body而不是StaticBody. 这可以通过简单地检查该函数是否存在于对象中来完成:if('setVelocity' in this.body) {  this.body.setVelocity(0, 0);}更具体地说,我们可以通过以下方式检查该对象是否是预期对象的实例:if(this.body instanceof Phaser.Physics.Arcade.Body) {  this.body.setVelocity(0, 0);}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript