# Distance from a point to a rectangle

This topic is 2970 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Can anyone help?

I'm looking for an explanation on how to calculate the shortest distance from a point to a rectangle in 3D.
I've had a good look around and I can't find any explanation of it that I can get my head around. If someone knows how to do this and could pseudo code / point me in the right direction etc etc it would be ridiculously helpful.

##### Share on other sites
Quote:

Ah cool, but erm what does this mean exactly.
2. Clamp each element of the point vector to the corresponding [min,max] range of the rectangle.

My assumption would be that you are checking the distance from the maximum and minimum x,y,z values for the verts of the rectangle.

##### Share on other sites
Oh actually nevermind i get it now.

Let this be lesson to everyone to not code with a hangover.

##### Share on other sites
Ah nice, I was ready to post this link where you can find info on coordinate transformations. Another but slower way to do it would be to just search the surface for the closest point by doing the 2D analogue of a binary search.

##### Share on other sites
If you only need the distance, I've used this approach before:

float distance(const Box& r, const Point& p) {
float squared_dist = 0.0f;

if(p.X > r.Max.X)
squared_dist += (p.X - r.Max.X)*(p.X - r.Max.X);
else if(p.X < r.Min.X)
squared_dist += (r.Min.X - p.X)*(r.Min.X - p.X);

if(p.Y > r.Max.Y)
squared_dist += (p.Y - r.Max.Y)*(p.Y - r.Max.Y);
else if(p.Y < r.Min.Y)
squared_dist += (r.Min.Y - p.Y)*(r.Min.Y - p.Y);

if(p.Z > r.Max.Z)
squared_dist += (p.Z - r.Max.Z)*(p.Z - r.Max.Z);
else if(p.Z < r.Min.Z)
squared_dist += (r.Min.Z - p.Z)*(r.Min.Z - p.Z);

return sqrt(squared_dist);
}

1. 1
2. 2
3. 3
Rutin
22
4. 4
5. 5

• 12
• 19
• 14
• 9
• 9
• ### Forum Statistics

• Total Topics
632929
• Total Posts
3009285
• ### Who's Online (See full list)

There are no registered users currently online

×