【问题标题】:Checking if a point is inside a rotated rectangle检查一个点是否在旋转的矩形内
【发布时间】:2013-06-12 17:33:56
【问题描述】:

我知道这个问题已经被问过几次了,我已经阅读了很多关于这个问题的帖子。但是我正在努力让它发挥作用。

    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;
    }

【问题讨论】:

  • 如果不知道应用于纹理的变换,这是无法验证的。创建一个新矩阵是一种代码味道。您应该使用最初在纹理上使用的矩阵。并且不旋转鼠标位置,而是将纹理向后旋转,使其再次成为矩形。

标签: c# math graphics xna geometry


【解决方案1】:

让点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 * By - Bx * Cy) + (Ax * Cy - Cx * Ay) ) / 2

【讨论】:

    【解决方案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;
    }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-09
      • 1970-01-01
      • 2021-10-01
      • 2016-06-07
      • 2012-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多