Jump to content
  • Advertisement
Sign in to follow this  

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.

If you intended to correct an error in the post then please contact us.

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.

Thanks in advance.

Share this post

Link to post
Share on other sites
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.

Share this post

Link to post
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 this post

Link to post
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);

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!