Distance from a point to a rectangle

Started by
4 comments, last by Zipster 13 years, 8 months ago
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.

Thanks in advance.
Advertisement
What about this topic?
Quote:Original post by D_Tr
What about this topic?


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.

Oh actually nevermind i get it now.

Let this be lesson to everyone to not code with a hangover.
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.
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);}

This topic is closed to new replies.

Advertisement