我试图写一个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)我是否已经正确地实现了我链接的算法,或者如果我确实如何解释这一点?
有什么建议吗?
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;
};
bool
overlap(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;
}
A和B是两个矩形。C是它们的覆盖矩形。
four points of A be (xAleft,yAtop),(xAleft,yAbottom),(xAright,yAtop),(xAright,yAbottom)
four points of A be (xBleft,yBtop),(xBleft,yBbottom),(xBright,yBtop),(xBright,yBbottom)
A.width = abs(xAleft-xAright);
A.height = abs(yAleft-yAright);
B.width = abs(xBleft-xBright);
B.height = abs(yBleft-yBright);
C.width = max(xAleft,xAright,xBleft,xBright)-min(xAleft,xAright,xBleft,xBright);
C.height = max(yAtop,yAbottom,yBtop,yBbottom)-min(yAtop,yAbottom,yBtop,yBbottom);
A and B does not overlap if
(C.width >= A.width + B.width )
OR
(C.height >= A.height + B.height)
它考虑到所有可能的情况。
如果矩形重叠,那么重叠面积将大于零。现在让我们求出重叠区域:
如果它们重叠,那么overlap-rect的左边缘将是max(r1。X1, r2.x1)和右边将是min(r1。x2, r2.x2)。所以重叠的长度是min(r1)X2 r2 X2 - max(r1。x1, r2.x1)
所以面积是:
area = (max(r1.x1, r2.x1) - min(r1.x2, r2.x2)) * (max(r1.y1, r2.y1) - min(r1.y2, r2.y2))
如果area = 0,则它们不重叠。
很简单,不是吗?
更容易检查一个矩形是否完全在另一个矩形之外,如果它是其中之一
在左边……
(r1.x + r1.width < r2.x)
或者在右边…
(r1.x > r2.x + r2.width)
或者在上面…
(r1.y + r1.height < r2.y)
或者在底部…
(r1.y > r2.y + r2.height)
对于第二个矩形,它不可能与它碰撞。因此,要有一个返回布尔值的函数,表示矩形是否碰撞,我们只需通过逻辑or组合这些条件,并对结果求反:
function checkOverlap(r1, r2) : Boolean
{
return !(r1.x + r1.width < r2.x || r1.y + r1.height < r2.y || r1.x > r2.x + r2.width || r1.y > r2.y + r2.height);
}
如果只在触摸时得到阳性结果,我们可以通过“<=”和“>=”来更改“<”和“>”。
对于那些使用中心点和一半大小的矩形数据的人,而不是典型的x,y,w,h或x0,y0,x1,x1,下面是你可以这样做:
#include <cmath> // for fabsf(float)
struct Rectangle
{
float centerX, centerY, halfWidth, halfHeight;
};
bool isRectangleOverlapping(const Rectangle &a, const Rectangle &b)
{
return (fabsf(a.centerX - b.centerX) <= (a.halfWidth + b.halfWidth)) &&
(fabsf(a.centerY - b.centerY) <= (a.halfHeight + b.halfHeight));
}