This question is similar to another one about axis-aligned rectangles. However, I specifically want to calculate this for rotated rectangles.
I have a rectangle with a (cx, cy) for the center point and a width, and height, and a (x, y) for the test point, as well as a θ for the angle of rotation.
What's the fastest way to determine the distance between that point, and the nearest edge of the rectangle? If the point is inside the rectangle, the distance should be zero.
I believe that there is going to be only a small change to the equation in the linked question, but I have no idea what it might be.
Answer
Just rotate the point at an angle of -θ around the center of the rectangle.
relx = x-cx
rely = y-cy
rotx = relx*cos(-theta) - rely*sin(-theta)
roty = relx*sin(-theta) + rely*cos(-theta)
dx = max(abs(rotx) - width / 2, 0);
dy = max(abs(roty) - height / 2, 0);
return dx * dx + dy * dy;
Also, remember this is still the distance squared, so you need to take the square root of it to get the actual distance
No comments:
Post a Comment