我可能錯過了一些非常簡單的東西,但我不明白爲什麼此函數總是返回true,並且即使兩個對象彼此不接近時也會記錄這兩個對象。 我的代碼:碰撞檢測函數總是返回true
var collideRect=function(obj1, obj2){
var x1=obj1.x,y1=obj1.y,x2=obj2.x, y2=obj2.y;
var b1=obj1.breadth,h1=obj1.height;
var b2=obj2.breadth,h2=obj2.height;
var xCollide, yCollide;
// determine if the x values are closer than half the breadth of each rectangle to each other
if(x1+b1/2>x2-b2/2||x1-b1/2<x2+b2/2){xCollide=true};
// determine if the y values are closer than half their heights from one another
if(y1+h1/2>y2-h2/2||y1-h1/2<y2+h2/2){yCollide=true};
if(xCollide&&yCollide){
console.log(JSON.stringify(obj1)+". "+JSON.stringify(obj2)) ;
return true;
};
}
這些值都不是0。該功能需要具有以下屬性的對象: 寬度, 高度, x, y。 這些都是正數。我已經檢查了每個聲明的操作順序,它們都很好。
這個問題太不明確,無法證實。請參閱:https://stackoverflow.com/help/mcve幫助嘗試並修復您的問題 – Deckerz
可能是那些if語句。記住數學的PEMDAS/BODMAS?在你的if語句中,例如x1 + b1/2將執行b1/2 + x1,因爲沒有括號。分部在加入之前。 –
操作順序很好 – user7951676