2014-03-13 139 views
3

我一直在使用我讀過的文章中的教程編寫這個碰撞檢測系統,而我只是無法讓我的生活得到正確的功能。 下面是對於初學者代碼:2D碰撞檢測分辨率

BoundingBox aBox; 
aBox.Convert(a); 
BoundingBox bBox; 
bBox.Convert(b); 

Vector2 aMin = aBox.GetTopLeft(); 
Vector2 aMax = aBox.GetBotRight(); 
Vector2 bMin = bBox.GetTopLeft(); 
Vector2 bMax = bBox.GetBotRight(); 

Vector2 minDistance; 

float left = (bMin.x - aMax.x); 
float right = (bMax.x - aMin.x); 
float top = (bMin.y - aMax.y); 
float bottom = (bMax.y - aMin.y); 

// Check for intersection internally 
if (left > 0 || right < 0) return; 
if (top > 0 || bottom < 0) return; 

// Find the minDistance 
if (abs(left) < right) 
    minDistance.x = left; 
else 
    minDistance.x = right; 

if (abs(top) < bottom) 
    minDistance.y = top; 
else 
    minDistance.y = bottom; 

// Null axis with biggest value 
if (abs(minDistance.x) < abs(minDistance.y)) 
    minDistance.y = 0; 
else 
    minDistance.x = 0; 

現在的問題是,性格是好的步行和擁抱塊的頂部和塊的底部,但是一旦他走了兩個街區,他陷入他們之間。巧合的是,走下來工作非常好。只是想知道如果有人有解決這個問題,它將不勝感激!

這裏有一個GIF,以更好地顯示的問題:

enter image description here

+0

:D試着用省略號 – dgrat

回答

0

嗯,這可能是更多的是解決辦法比實際修復,但在處理輸入的時候,你可以檢查是否有空間你正在轉向的方向。

如果您移動到左上方,可以檢查左側是否有空間,如果沒有空間,則只應用運動的垂直分量。同樣適用於四個方向。

大多數這類錯誤來自於rouding數字的工作方式,如果你想要一個一致的好的行爲,就像我剛剛給你的例子一樣,努力避免這些舍入數量情況。