2 回答

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);?
}

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);
}
添加回答
舉報