Checking if a point is inside a rotated rectangle

后端 未结 2 1705
予麋鹿
予麋鹿 2021-01-13 09:17

I know this question has been asked a few times before, and I have read various posts about this. However I am struggling to get this to work.

    bool isCl         


        
2条回答
  •  悲哀的现实
    2021-01-13 09:23

    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.

提交回复
热议问题