2017-09-06 52 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