15,668,517 members
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 &amp;&amp;
rotatedPoint.X &gt; Location.X &amp;&amp;
rotatedPoint.X &lt; Location.X + Texture.Width &amp;&amp;
rotatedPoint.Y &gt; Location.Y &amp;&amp;
rotatedPoint.Y &lt; Location.Y + Texture.Height)
{
Location = origLoc;
return true;
}
Location = origLoc;
return false;
}
```
Posted

## Solution 1

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.

v3
Comments
[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)

Top Experts
Last 24hrsThis month
 OriginalGriff 388 Graeme_Grant 70 Richard MacCutchan 60 Dave Kreskowiak 58 Richard Deeming 50
 OriginalGriff 1,065 Richard MacCutchan 177 Patrice T 110 Graeme_Grant 70 Richard Deeming 50

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