1
\$\begingroup\$

How would I get the closest distance between a square's edge and a point in 2D, if I only have the points coordinates, and the coordinates of the square and it's size?

\$\endgroup\$
  • 1
    \$\begingroup\$ Have you tried Google for "distance line to point"? It is a quite common problem that has been solved many times. Since a square is 4 line segments, it should be fairly easy to figure out the closest point. What have you tried so far? \$\endgroup\$ – Felsir May 15 at 19:20
  • \$\begingroup\$ i know how to do circles, but i count even think of how to do squares. \$\endgroup\$ – Ian Os May 16 at 23:27
2
\$\begingroup\$
float DistanceFromRectangle(Vector2 point, Vector2 center, Vector2 size, float angle) {

    // First, transform the point into the rectangle's local coordinate space.
    Vector2 offset = Rotate(point - center, -1 * angle);

    // Take the absolute value of this offset, on x and y, and subtract the size.
    // This gives zero on the edge, increasing positively as we move away.
    // Clamp out any values less than zero.
    Vector2 outside = Max(Abs(offset) - size/2, Vector2.zero);

    // Return the length of this vector, which is our distance to the closest point
    // on the square's edges or corners, and zero inside the square.
    return Length(outside);
}
\$\endgroup\$
  • \$\begingroup\$ thanks! though could you translate that into math that doesn’t use vectors? \$\endgroup\$ – Ian Os May 16 at 23:26
  • \$\begingroup\$ Repeat everything for x and y and you're done. \$\endgroup\$ – DMGregory May 16 at 23:27
0
\$\begingroup\$

Thank you Felsir and DMGregory, I just googled 'distance point to square' and I found a already existing stackexchange question about this. How do I calculate distance between a point and an axis-aligned rectangle? Thanks!!

\$\endgroup\$
  • 1
    \$\begingroup\$ Next time, search before asking. ;) It's a lot faster for everyone involved. \$\endgroup\$ – DMGregory May 17 at 0:25
  • \$\begingroup\$ Sorry, I had looked, but not thoroughly enough. I'll make sure I can't find anything before asking. \$\endgroup\$ – Ian Os May 17 at 16:53

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.