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.


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

  • \$\begingroup\$ There is a minor problem with your code, consider this case: the point is exactly at (cx,cy). In this case, dx will become "width/2" and dy will become "height/2". Instead of computing squared distance, you should fix this by some conditions. \$\endgroup\$ – Ali1S232 Oct 26 '14 at 9:21
  • \$\begingroup\$ also it doesn't need to be rotated around the center, and point in plane will do, as long as you rotate everything (including rectangle itself) \$\endgroup\$ – Ali1S232 Oct 26 '14 at 9:23
  • \$\begingroup\$ @Ali.S I don't see it. If rotx is 0 then dx = max(-width/2,0) which will be 0. Assuming width and height are positive, which I am. Also, I am implicitly rotating the rectangle, I just don't do it explicitly because the width and the height stay the same, so there's no reason. \$\endgroup\$ – PeterT Oct 26 '14 at 9:35
  • \$\begingroup\$ Can you explain why I need to rotate -θ degrees, why wouldn't just θ work? \$\endgroup\$ – BitNinja Oct 26 '14 at 20:43
  • \$\begingroup\$ @BitNinja I imagined how to reset the scene so that you have an axis aligned rectangle, with a point that has the same distance to it. So rotating both by -θ was the first thing that came to my mind (but like I said we don't need to do anything for the rectangle, since we just imagine rotating it along into and axis-aligned position). \$\endgroup\$ – PeterT Oct 26 '14 at 20:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.