Click here to Skip to main content
15,904,346 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Ok I need to check if a mouse click has clicked on a rectangle, obviously this is trivial when the rectangle hasn't been rotated, but when it has it gets harder.

After reading quite a few posts I believe you have to reverse the rotation of the point and rectangle (I have moved rectangle to origin so it has the same rotation centre as the matrix), then simply do a normal bounds check.

This is what I have got so far, however it doesn't work:
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;

1 solution

A rectangle has four Points. You have to get the position of those four points after rotation by multiplying the position of point with rotation matrix. Then create a 2D plane from every two points which make a wall of the rectangle. Now you can check whether the mouse position is in front of plane or behind the plane. If it is behind the all the planes then it means mouse has collided with the rectangle. Hope this helps. I just gave you solution in very short words.

If you need code how to create plane from two points and how to check if a point is behind/front of a plane. You can find it on google very easily.
Share this answer
[no name] 16-Jun-13 17:21pm    
Is that not exactly what I have done in the latter part of my code sample

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900