我正在尝试编写一个 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 1
int rot_x, rot_y;
rot_x = -arrRect1[3];
rot_y = arrRect1[2];
// point on rotated edge
int pnt_x, pnt_y;
pnt_x = arrRect1[2];
pnt_y = arrRect1[3];
// test point, a from rect 2
int 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)我是否已经正确实现了我链接到的算法,或者我是否确实做了如何解释这个?
有什么建议么?
原文由 Rob Burke 发布,翻译遵循 CC BY-SA 4.0 许可协议
或者,使用笛卡尔坐标
(X1是左坐标,X2是右坐标, 从左到右增加,Y1是上坐标,Y2是下坐标, 从下到上增加——如果这不是你的坐标系[例如,大多数计算机有Y方向反转], 交换下面的比较)…
假设你有 Rect A 和 Rect B。证明是矛盾的。四个条件中的任何一个都保证 不存在重叠:
所以非重叠的条件是
因此,重叠的充分条件是相反的。
德摩根定律说
Not (A or B or C or D)
与Not A And Not B And Not C And Not D
相同所以使用德摩根,我们有
这相当于:
RectA.Left < RectB.Right
],和RectA.Right > RectB.Left
],和RectA.Top > RectB.Bottom
],和RectA.Bottom < RectB.Top
]注 1 :很明显,同样的原理可以扩展到任意数量的维度。
注意 2 :计算仅一个像素的重叠也应该是相当明显的,将边界上的
<
和/或>
更改为<=
或一个>=
。注意 3 :当使用笛卡尔坐标 (X, Y) 时,此答案基于标准代数笛卡尔坐标(x 从左到右增加,Y 从下到上增加)。显然,如果计算机系统可能以不同方式处理屏幕坐标(例如,从上到下增加 Y,或从右到左增加 X),则需要相应地调整语法/