c0op
c0op

Reputation: 15

C++ Get Point on 3D Vector with Shortest Distance to given Point


I have given a 3D Line which is represented with two 3D Vectors (start-, endpoint), all in C++

vec3 x1 = [x,y,z]
vec3 x2 = [x,y,z]

also i have a 3D Point

vec3 x0 = [x,y,z]

I want to find the Point p which has the shortest distance d to my Point x0 from my given line.
Here's an image as an example:

Get Point **P** on given Line Segment

Thanks for your help!

Upvotes: 0

Views: 2722

Answers (2)

shadow_map
shadow_map

Reputation: 343

You could project the vector x1->x0 onto the vector x1->x2, and then your point p will be x1 + projected vector. Something like this:

if (x1 == x2)
    return x1;

vector x1x0 = x0 - x1;
vector x1x2 = x2 - x1;

float t = x1x0.dot(x1x2) / x1x2.SquaredLength();

if (t <= 0.0)
    return x1;
else if(t >= 1.0)
    return x2;
else
    return x1 + t * x1x2;

Upvotes: 0

user3235832
user3235832

Reputation:

Take the equation of your line

p = x1 + t (x2 - x1)

The closest point p is such that the vector x0 - p is perpendicular to the line. (You can prove this with Pythagoras / elementary calculus).

Therefore you need

(p - x0) . (x2 - x1) = 0

where . is the dot product.

(x1 - x0 + t (x2 - x1)) . (x2 - x1) = 0

t = - [ (x1 - x0) . (x2 - x1) ] / |x2 - x1|^2

where |x2 - x1| is the magnitude.

Plug this into the first equation to find the p you want.

(PS sorry I couldn't format the equations)

Upvotes: 1

Related Questions