1

我有一个数学问题。

当一个矩形(或其中一个)都没有角度并且完全适合网格时,我可以检查一个矩形是否在另一个矩形的范围内。但是一旦我改变了它们两个的角度,一切都会走下坡路。

这就是我的意思 - 右边的工作完美无缺,但左边的没有那么多: 在此处输入图像描述

4

4 回答 4

1

It's possible to do this without using either rotations (which means calling trig functions) or normalizing vectors (which requires a sqrt).

Suppose your rectangle is defined by points a, b, c, d in clockwise order. A point is inside the rectangle if it is on the righthand side of each of the vectors ab, bc, cd and da.

You can test point p against vector ab by taking the dot product of the vector ap with a vector perpendicular to ab, which you can get just by swapping the x and y and flipping one of the signs. The sign of the dot product tells you what side of the vector you are on.

If the signs are all positive then the point is inside the rectangle. You don't need to normalize because you are only checking the sign, not the magnitude.

float pointToVector(Vec2 p, Vec2 a, Vec2 b)
{
    Vec2 n = new Vec2(b.y - a.y, a.x - b.x); // no need to normalize

    return n.dot(p - a);
}

bool pointInRect(Vec2 p, Vec2 a, Vec2 b, Vec2 c, Vec2 d)
{
    return (pointToVector(p, a, b) > 0) && // can short-circuit
       (pointToVector(p, b, c) > 0) &&
       (pointToVector(p, c, d) > 0) &&
       (pointToVector(p, d, a) > 0));
}

Note that this is actually an arbitrary point-in-4-sided-convex-polygon test. You could optimize it for rectangles by taking advantage of the fact that ab and cd are parallel, as are bc and da, so you can reuse the perpendicular vectors but reverse the sign of the check. That makes the code a little more complicated however. Also, the above assumes a co-ordinate system with y increasing going up. If not then change the the comparisons to < or define the rectangle in anti-clockwise order.

于 2016-05-30T07:27:04.737 回答
0

我建议只使用蒂姆的答案,而不是对轮换如此无知。但是,如果您真的太强迫症,您可以尝试以下基于矢量的方法。

由于矩形的边是垂直的,您可以将它们用作(正交)坐标系。

在此处输入图像描述

新坐标轴:

在此处输入图像描述

变换坐标:

在此处输入图像描述

检查:

在此处输入图像描述

于 2016-05-30T01:56:37.507 回答
0

您可以旋转两个矩形,使一个矩形与网格对齐。首先,计算两个矩形的旋转度数:

angle = arc tan(ength of long side / length of short side)
        arc tan(11 / 7)
      = 57.5 degrees

现在您知道绿色三角形的长边与 x 轴平行,逆时针方向为 57.5 度。因此,您可以将两个矩形顺时针旋转 57.5 度以获得您可以处理的配置。请参阅此处了解如何执行此操作。

于 2016-05-30T01:04:05.240 回答
0

在此处输入图像描述

P = a A + b B

求解ab。P 在矩形内,如果a < 1 && b < 1

于 2016-05-30T10:01:35.467 回答