2017-09-06 55 views
0

我可能錯過了一些非常簡單的東西,但我不明白爲什麼此函數總是返回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。 這些都是正數。我已經檢查了每個聲明的操作順序,它們都很好。

+0

這個問題太不明確,無法證實。請參閱:https://stackoverflow.com/help/mcve幫助嘗試並修復您的問題 – Deckerz

+0

可能是那些if語句。記住數學的PEMDAS/BODMAS?在你的if語句中,例如x1 + b1/2將執行b1/2 + x1,因爲沒有括號。分部在加入之前。 –

+0

操作順序很好 – user7951676

回答

1

您的if語句不正確。請參閱下面的調整算法和基本控制檯聲明。

基本上,您需要檢測任何邊緣之間是否沒有空間。如果沒有空間,則說明發生了碰撞。

分解如下:

Step1。

檢查矩形1的左邊緣。

如果矩形1的左邊緣小於矩形2的右邊緣(x2 + b2),矩形1的左邊緣和矩形2的右邊緣可能會出現交叉。

Step2。

檢查矩形1的右側。

如果rectangle1的右側大於rectangle2的左側,則rectangle1與rectangle2左側的rectangle2相交。我們使用& &檢測到這兩個條件均爲真,以確保發生了碰撞。

我們做兩個矩形的y座標完全相同的檢查,以達到檢測矩形是否相交在y平面..

var collideRect = function (obj1, obj2) { 
 
\t var collision = false; 
 

 
\t var x1 = obj1.x, 
 
\t y1 = obj1.y, 
 
\t x2 = obj2.x, 
 
\t y2 = obj2.y; 
 

 
\t var b1 = obj1.breadth, 
 
\t h1 = obj1.height; 
 

 
\t var b2 = obj2.breadth, 
 
\t h2 = obj2.height; 
 

 
\t var xCollide, 
 
\t yCollide; 
 
     // if left edge of rect1 is left of the left edge of rect2 plus its 
 
     // width AND left edge of rect1 plus rect1's width is greater than 
 
     // the left edge of rect2, we have an x-coordinate collision. 
 
     // if either set of conditions is false, the rects don't overlap. 
 
\t if (x1 < x2 + b2 && x1 + b1 > x2) { 
 
\t \t xCollide = true; 
 
\t } 
 
    // same as the x check but on the y plane 
 
\t if (y1 < y2 + h2 && h1 + y1 > y2) { 
 
\t \t yCollide = true; 
 
\t } 
 

 
\t if (xCollide && yCollide) { 
 
\t \t console.log(JSON.stringify(obj1) + ". " + JSON.stringify(obj2)); 
 
\t \t collision = true; 
 
\t } 
 
\t return collision; 
 
} 
 

 
// test 
 
var rect1 = { 
 
\t x: 5, 
 
\t y: 5, 
 
\t breadth: 50, 
 
\t height: 50 
 
}; 
 
var rect2 = { 
 
\t x: 20, 
 
\t y: 10, 
 
\t breadth: 10, 
 
\t height: 10 
 
}; 
 

 
console.assert(collideRect(rect1, rect2) === true); // collision 
 

 
var rect3 = { 
 
\t x: 55, 
 
\t y: 55, 
 
\t breadth: 50, 
 
\t height: 50 
 
}; 
 
var rect4 = { 
 
\t x: 20, 
 
\t y: 10, 
 
\t breadth: 10, 
 
\t height: 10 
 
}; 
 

 
console.assert(collideRect(rect3, rect4) === false); // no collision

+0

如果矩形的大小相等,我能理解它的工作原理嗎?但是我明白爲什麼它對不同大小的矩形有效 – user7951676

+0

它檢查座標位置並使用寬度和每個的高度作爲偏移量。如果這些數字集合中的任何一個相交(在相同範圍內的土地),則它檢測到碰撞。我會用更好的解釋來更新答案。 –

+0

謝謝,我明白現在好多了,出於興趣,還有很多其他基本算法用於檢測不同角度的其他形狀或形狀之間的變形? – user7951676