How to figure out if a point is inside the bounds of a rotated rectangle

73 Views Asked by At

I'm trying to figure out an approach (or a formula) to determine if a point (x,y) is inside the bounds of a rotated rectangle.

rotated rectangle graphic

For this test we can assume that the rectangle is centered on the axis, has a width of w and a height of h, and an angle of θ. I need a test to see if a point (A or B in the graphic) are inside the rectangle or not. In the graphic A is not and B is.

The actual goal though is to constrain a point to stay inside the rectangle.

I'm not a straight up mathematician.. I'm a software guy. So I deal with math all the time but I often come up with a coding approach to solve a problem.

One idea I have for an approach here is this: When the box isn't rotated it's a simple bounds test..

if B.x > w/2 then B.x=w/2
if B.x < -w/2 then B.x=-w/2
if B.y > h/2 then B.y=w/2
if B.y < -h/2 then B.y=-w/2

So I could rotate B (around the center of the rectangle) by -θ which essentially rotates the 'world' so that the rectangle isn't rotated. Basically move things into an unrotated space. Then do the above simple tests on the modified B. Then after bounding it inside the rectangle, rotate the point back by θ to put it back in the original space.

The other idea I had was to do something with vectors. Consider that B is a vector from the center of the rectangle. Then shorten the length of the vector (like normalize it) to a length that constrains it inside the rectangle. That seems more complex because it would require that I calculate the length vector B can be at each rotation.

Any ideas?