2

当矩形可以有不同的原点时,如何检查一个点是否在旋转矩形内?这基本上是我现在使用的:

struct Point 
{
    float x;
    float y;
};

struct Rectangle
{
    float x;
    float y;
    float w;
    float h;
    float origin;
    float rotation; // In degrees
};

bool contains(const Rectangle& rect, const Point& point)
{
    float c = std::cos(toRadians(-rect.rotation));
    float s = std::sin(toRadians(-rect.rotation));

    float x  = rect.x;
    float y  = rect.y;
    float w  = rect.w;
    float h  = rect.h;

    float rotX = x + c * (point.x - x) - s * (point.y - y);
    float rotY = y + s * (point.x - x) + c * (point.y - y);

    float lx = x - w / 2.f;
    float rx = x + w / 2.f;
    float ty = y - h / 2.f;
    float by = y + h / 2.f;

    return lx <= rotX && rotX <= rx && ty <= rotY && rotY <= by;
}

当原点位于矩形的中心但不在任何其他原点(我已经测试过)时,此代码确实有效。我怎样才能使它在原点例如在矩形的左上角时也可以工作?

4

0 回答 0