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