Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 矩形碰撞检测_C++_Algorithm_Collision Detection - Fatal编程技术网

C++ 矩形碰撞检测

C++ 矩形碰撞检测,c++,algorithm,collision-detection,C++,Algorithm,Collision Detection,这个算法正确吗 class Rectangle{ public: float x, y, width, height; // (x,y) is the lower left corner of the rectangle }; bool矩形::colidesWith(其他矩形){ 如果(x+width

这个算法正确吗

class Rectangle{
public:
   float x, y, width, height;
   // (x,y) is the lower left corner of the rectangle
};
bool矩形::colidesWith(其他矩形){
如果(x+width
如果矩形被填充(即,其中一个在另一个内的情况被视为碰撞)。

是的。你可以把它看作是超平面分离定理的一个特例,它是这个问题的一般形式。您正在将这些矩形投影到X轴和Y轴上,然后检查生成的线段之间是否有一定的间隔。

对于我来说,更直观的方法是:

bool Rectangle::colidesWith(Rectangle other) {
   if (x+width < other.x) return false; // "other" is on the far right
   if (other.x+other.width < x) return false; //"other" is on the far left
   if (y+height < other.y) return false // "other" is up
   if (other.y+other.height < y) return false // "other" is down
   return true;
}
(最大值(r1.x,r2.x)<最小值(r1.x+r1.w,r2.x+r2.w))&&
(最大值(r1.y,r2.y)<最小值(r1.y+r1.h,r2.y+r2.h))

事实上,这可以推广到任何维度。

ve+Y向上吗?如果是这样的话,看起来还可以。你的意思是如果它们没有被填充,而其中一个在另一个里面,那么我的算法就不起作用了?在所有其他情况下都有效吗?据我所知,是的。还有,第一个问题是。@l19-矩形已填充。如果一个矩形在另一个矩形内,则该矩形将被视为碰撞。如果那是你想要的,那么一切都很好。你只需要改变一些你不想要的行为。
( max(r1.x, r2.x) < min(r1.x+r1.w, r2.x+r2.w) ) &&
( max(r1.y, r2.y) < min(r1.y+r1.h, r2.y+r2.h) )