Checking if a point is inside a rotated rectangle

风流意气都作罢 提交于 2019-12-05 12:04:16
Alexander Gorelik

Let point P(x,y), and rectangle A(x1,y1), B(x2,y2), C(x3,y3), D(x4,y4).

  • Calculate the sum of areas of △APD, △DPC, △CPB, △PBA.

  • If this sum is greater than the area of the rectangle:

    • Then point P(x,y) is outside the rectangle.
    • Else it is in or on the rectangle.

The area of each triangle can be calculated using only coordinates with this formula:

Assuming the three points are: A(x,y), B(x,y), C(x,y).

Area = abs( (Bx * Ay - Ax * By) + (Cx * Bx - Bx * Cx) + (Ax * Cy - Cx * Ay) ) / 2

I assume that Location is the rectangle's rotation center. If not, please update your answer with an appropriate figure.

What you want to do is expressing the mouse location in the local system of the rectangle. Therfore, you could do the following:

bool isClicked()
{
    Matrix rotationMatrix = Matrix.CreateRotationZ(-Rotation);
    //difference vector from rotation center to mouse
    var localMouse = new Vector2(Game1.mouseState.X, Game1.mouseState.Y) - Location;
    //now rotate the mouse
    localMouse = Vector2.Transform(localMouse, rotationMatrix);

    if (Game1.mouseState.LeftButton == ButtonState.Pressed &&
        rotatedPoint.X > -Texture.Width  / 2 &&
        rotatedPoint.X <  Texture.Width  / 2 &&
        rotatedPoint.Y > -Texture.Height / 2 &&
        rotatedPoint.Y <  Texture.Height / 2)
    {
        return true;
    }
    return false;
}

Additionally, you may want to move the check if the mouse is pressed to the beginning of the method. If it is not pressed, you don't have to calculate the transformation etc.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!