# Getting closest distance between a square's edge and a point 2D

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?

• 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? – Felsir May 15 at 19:20
• i know how to do circles, but i count even think of how to do squares. – Ian Os May 16 at 23:27

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);
}

• thanks! though could you translate that into math that doesn’t use vectors? – Ian Os May 16 at 23:26
• Repeat everything for x and y and you're done. – DMGregory May 16 at 23:27

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!!

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