I'm setting up collision detection and I have Walls which store their positions as rectangles. I need to figure out the distance from a Vector2 to the nearest side of a rectangle. If this was two Vector2's I could just do Vector2.Distance() but I can't find similar methods for Vector2s and Rectangles. Here is an image to illustrate what I need:

So the red dot would be my Vector2 and the blue would be my Rectagle, and I need to get the distance of the orange line. Once I have this I can check the distance for my collision detection.


For arbitrary shapes

The basic algorithm goes like this:

// Gets the distance from a point to a shape made of line segments.
float GetDistance(Shape shape, Vector2 point):
    min_dist = float.max;
    foreach LineSegment line in shape:
         dist = GetDistance(line, point);
         min_dist = min(min_dist, dist);
    return min_dist;

// Gets the distance from a line segment to a point
float GetDistance(LineSegment, Vector2 point):

The distance from a line segment to a point is also pretty easy to find.

For axis aligned rectangles

Axis aligned rectanges (ie, non-rotated) have the nice property that they're already rotated into the same coordinate frame as the point. This makes the problem a lot easier. Suppose the rectangle has the parameterization:

[min_x, min_y, max_x, max_y]

You can clamp to the nearest point in the rectangle, and find the distance to that point. The nearest point on the rectangle is given by:

nearest = [point.x, point.y];
if (point.x < min_x)
   nearest.x = min_x;
else if(point.x > max_x)
   nearest.x = max_x;

if(point.y < min_y)
    nearest.y = min_y;
else if(point.y > max_x)
    nearest.y = max_y;

And the distance is given by:

 (nearest - point).Length();

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.