亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 TypeScript 的 Phaser 上的聯合類型不存在屬性

使用 TypeScript 的 Phaser 上的聯合類型不存在屬性

至尊寶的傳說 2023-08-05 19:30:06
用 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'。顯然,精靈的主體可以用于Body、StaticBody或BodyType對象。檢查文檔,類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如果是這樣,有沒有辦法讓我指定我正在使用什么類型?我嘗試解析無濟于事。
查看完整描述

2 回答

?
精慕HU

TA貢獻1845條經驗 獲得超8個贊

錯誤消息表明您的玩家主體是這些類型之一'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);?

}


查看完整回答
反對 回復 2023-08-05
?
慕姐4208626

TA貢獻1852條經驗 獲得超7個贊

正如 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);

}


查看完整回答
反對 回復 2023-08-05
  • 2 回答
  • 0 關注
  • 147 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號