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?
-
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\$– FelsirMay 15, 2019 at 19:20
-
\$\begingroup\$ i know how to do circles, but i count even think of how to do squares. \$\endgroup\$– Ian OsMay 16, 2019 at 23:27
2 Answers
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);
}
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!!
-
1\$\begingroup\$ Next time, search before asking. ;) It's a lot faster for everyone involved. \$\endgroup\$– DMGregory ♦May 17, 2019 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 OsMay 17, 2019 at 16:53