繁体   English   中英

大肠杆菌检测功能始终返回true

[英]Function for colision detection always returns 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;
   }; 
}

所有值都不是ever0。 该函数将对象带到每个具有以下属性的对象:宽度,高度,x,y。 这些都是正数。 我检查了每个语句的操作顺序,它们都很好。

您的if语句不正确。 有关调整后的算法和基本控制台声明,请参见下文。

本质上,您需要检测任何一条边缘之间是否没有空间。 如果没有空间,您将知道发生了碰撞。

细分如下:

第1步。

检查矩形1的左边缘。

如果矩形1的左边缘小于矩形2的右边缘(x2 + b2),则矩形1的左侧和矩形2的右侧可能有交集。

第2步。

检查矩形1的右侧。

如果矩形1的右侧大于矩形2的左侧,则矩形1在矩形2的左侧与矩形2相交。 我们使用&&来检测这两个条件都成立,以确保发生碰撞。

我们对两个矩形的y坐标进行了完全相同的检查,以检测矩形是否在y平面上相交。

 var collideRect = function (obj1, obj2) { var collision = false; 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; // 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. if (x1 < x2 + b2 && x1 + b1 > x2) { xCollide = true; } // same as the x check but on the y plane if (y1 < y2 + h2 && h1 + y1 > y2) { yCollide = true; } if (xCollide && yCollide) { console.log(JSON.stringify(obj1) + ". " + JSON.stringify(obj2)); collision = true; } return collision; } // test var rect1 = { x: 5, y: 5, breadth: 50, height: 50 }; var rect2 = { x: 20, y: 10, breadth: 10, height: 10 }; console.assert(collideRect(rect1, rect2) === true); // collision var rect3 = { x: 55, y: 55, breadth: 50, height: 50 }; var rect4 = { x: 20, y: 10, breadth: 10, height: 10 }; console.assert(collideRect(rect3, rect4) === false); // no collision 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM