确定两个矩形是否重叠?我正在尝试编写一个C+程序,它接受用户的以下输入来构造矩形(介于2到5之间):高度、宽度、x-pos、y-pos。所有这些矩形都将与x和y轴平行存在,即它们的所有边都有0或无穷大的斜率。我试着去实现这,这个有疑问,但我运气不太好。我目前的实现如下:// Gets all the vertices for Rectangle 1 and stores them in an array -> arrRect1
// point 1 x: arrRect1[0], point 1 y: arrRect1[1] and so on...
// Gets all the vertices for Rectangle 2 and stores them in an array -> arrRect2
// rotated edge of point a, rect 1int rot_x, rot_y;rot_x = -arrRect1[3];rot_y = arrRect1[2];
// point on rotated edgeint pnt_x, pnt_y;pnt_x = arrRect1[2]; pnt_y = arrRect1[3];
// test point, a from rect 2int tst_x, tst_y;tst_x = arrRect2[0];tst_y = arrRect2[1];
int value;value = (rot_x * (tst_x - pnt_x)) + (rot_y * (tst_y - pnt_y));cout << "Value: " << value;但是,我不太确定(A)我是否正确地实现了我链接到的算法,或者我是否准确地解释了这一点?有什么建议吗?
3 回答
心有法竹
TA贡献1866条经验 获得超5个赞
struct rect{ int x; int y; int width; int height;};bool valueInRange(int value, int min, int max){ return (value >= min) && (value <= max); }bool rectOverlap(rect A, rect B){ bool xOverlap = valueInRange(A.x, B.x, B.x + B.width) || valueInRange(B.x, A.x, A.x + A.width); bool yOverlap = valueInRange(A.y, B.y, B.y + B.height) || valueInRange(B.y, A.y, A.y + A.height); return xOverlap && yOverlap;}
慕虎7371278
TA贡献1802条经验 获得超4个赞
struct Rect{ Rect(int x1, int x2, int y1, int y2) : x1(x1), x2(x2), y1(y1), y2(y2) { assert(x1 < x2); assert(y1 < y2); } int x1, x2, y1, y2;};booloverlap(const Rect &r1, const Rect &r2){ // The rectangles don't overlap if // one rectangle's minimum in some dimension // is greater than the other's maximum in // that dimension. bool noOverlap = r1.x1 > r2.x2 || r2.x1 > r1.x2 || r1.y1 > r2.y2 || r2.y1 > r1.y2; return !noOverlap;}
添加回答
举报
0/150
提交
取消