我正在使用JavaScript的遊戲引擎,我目前正在研究碰撞系統。我制定了算法來解決與玩家發現的衝突,但我沒有得到預期的行爲。這裏是代碼:我的AABB碰撞檢測/解析代碼有什麼問題?
if (gameObjects [i].hasComponent ("BoxCollider") == true) {
for (var x = 0; x < gameObjects.length; x++) {
if (gameObjects [x].hasComponent ("BoxCollider") == true && gameObjects [i] != gameObjects [x]) {
if (gameObjects [i].transform.xPos - (gameObjects [i].getComponent ("BoxCollider").width/2) < gameObjects [x].transform.xPos + (gameObjects [x].getComponent ("BoxCollider").width/2) && gameObjects [i].transform.xPos + (gameObjects [i].getComponent ("BoxCollider").width/2) > gameObjects [x].transform.xPos - (gameObjects [x].getComponent ("BoxCollider").width/2) && gameObjects [i].transform.yPos - (gameObjects [i].getComponent ("BoxCollider").height/2) < gameObjects [x].transform.yPos + (gameObjects [x].getComponent ("BoxCollider").height/2) && gameObjects [i].transform.yPos + (gameObjects [i].getComponent ("BoxCollider").height/2) > gameObjects [x].transform.yPos - (gameObjects [x].getComponent ("BoxCollider").height/2)) {
//collision
if (gameObjects [i] == player) {
var xPenetration = 0;
var yPenetration = 0;
//i is left of x
if (gameObjects [i].transform.xPos < gameObjects [x].transform.xPos) {
xPenetration = -1 * ((/*i right edge*/gameObjects [i].transform.xPos + gameObjects [i].boxCollider.width/2) - (/*x left edge*/gameObjects [x].transform.xPos - gameObjects [x].boxCollider.width/2));
}
//i is right of x
else if (gameObjects [i].transform.xPos > gameObjects [x].transform.xPos) {
xPenetration = ((/*x right edge*/gameObjects [x].transform.xPos + gameObjects [x].boxCollider.width/2) - (/*i left edge*/gameObjects [i].transform.xPos - gameObjects [i].boxCollider.width/2));
}
//i is top of x
if (gameObjects [i].transform.yPos < gameObjects [x].transform.yPos) {
yPenetration = -1 * ((/*i bottom edge*/gameObjects [i].transform.yPos + gameObjects [i].boxCollider.height/2) - (/*x top edge*/gameObjects [x].transform.yPos - gameObjects [x].boxCollider.height/2));
}
//i is bottom of x
else if (gameObjects [i].transform.yPos > gameObjects [x].transform.yPos) {
yPenetration = ((/*x bottom edge*/gameObjects [x].transform.yPos + gameObjects [x].boxCollider.height/2) - (/*i top edge*/gameObjects [i].transform.yPos - gameObjects [i].boxCollider.height/2));
}
if (Math.abs (xPenetration) > Math.abs (yPenetration)) {
gameObjects [i].transform.xPos += xPenetration;
} else {
gameObjects [i].transform.yPos += yPenetration;
}
}
}
}
}
}
}
對不起,但「但我沒有得到預期的行爲。」不能幫助我們理解問題的原因,而是一個可運行的例子可以幫助我們 – InferOn
'我的代碼有什麼問題?'您的代碼沒有任何註釋表明目的/指定的行爲。你的代碼很難閱讀,特別是在SE的代碼窺視孔中。測試'gameObjects [i] == player'看起來不變:將其移出循環。縮小縮進級別 - 缺乏重構,使用'繼續'語句。在源代碼級別「消除」常見子表達式,例如'(gameObjects [i] .getComponent(「BoxCollider」)。width/2)'。在詢問調試支持時沒有說明必需和觀察到的行爲是解決問題的理由。 – greybeard
發生了什麼?它沒有檢測到碰撞嗎?它是否檢測到假陽性碰撞?它是否檢測到它,但不正確地迴應它? – samgak