检查点是否在旋转的矩形内

Har*_*vey 4 c# math graphics xna geometry

我知道这个问题之前曾被问过几次,我已经阅读过有关此问题的各种帖子.但是,我正在努力让这个工作.

    bool isClicked()
    {
        Vector2 origLoc = Location;
        Matrix rotationMatrix = Matrix.CreateRotationZ(-Rotation);
        Location = new Vector2(0 -(Texture.Width/2), 0 - (Texture.Height/2));
        Vector2 rotatedPoint = new Vector2(Game1.mouseState.X, Game1.mouseState.Y);
        rotatedPoint = Vector2.Transform(rotatedPoint, rotationMatrix);

        if (Game1.mouseState.LeftButton == ButtonState.Pressed &&
            rotatedPoint.X > Location.X &&
            rotatedPoint.X < Location.X + Texture.Width &&
            rotatedPoint.Y > Location.Y &&
            rotatedPoint.Y < Location.Y + Texture.Height)
        {
            Location = origLoc;
            return true;
        }
        Location = origLoc;
        return false;
    }
Run Code Online (Sandbox Code Playgroud)

Ale*_*lik 9

设点P(x,y),和矩形A(x1,y1),B(x2,y2),C(x3,y3),D(x4,y4).

  • 计算面积的总和?APD,?DPC,?CPB,?PBA.

  • 如果此总和大于矩形的面积:

    • 然后点P(x,y)外面的矩形.
    • 否则它矩形中或上面.

每个三角形的面积只能使用此公式的坐标计算:

假设三个点: A(x,y), B(x,y), C(x,y).

Area = abs( (Bx * Ay - Ax * By) + (Cx * Bx - Bx * Cx) + (Ax * Cy - Cx * Ay) ) / 2
Run Code Online (Sandbox Code Playgroud)


Nic*_*ler 2

我假设这Location是矩形的旋转中心。如果没有,请用适当的数字更新您的答案。

你想要做的是表达鼠标在矩形本地系统中的位置。因此,您可以执行以下操作:

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;
}
Run Code Online (Sandbox Code Playgroud)

此外,您可能希望将鼠标是否按下的检查移至方法的开头。如果没有按下,则不必计算变换等。