我可能错过了一些非常简单的东西,但我不明白为什么此函数总是返回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