Sign in to follow this  
sjf

Distance betwwen line and point? 0

Recommended Posts

sjf    130
Does anyone have a simple, quick and clean algorithm to find the shortest distance between a line (denoted by x1, z1, x2, z2) and a point (x0, z0)? Something to just cut ‘n’ paste?

Share this post


Link to post
Share on other sites
jyk    2094
Quote:
Does anyone have a simple, quick and clean algorithm to find the shortest distance between a line (denoted by x1, z1, x2, z2) and a point (x0, z0)?
Yes:

Vector2 O(x1, z1);
Vector2 D(x2-x1, z2-z1);
Vector2 diff(x0-x1, z0-z1);
float t = diff.Dot(D) / D.Dot(D);
if (t >= 1.0f) diff -= D;
else if (t >= 0.0f) diff -= t*D;
return diff.Dot(diff); // Squared length

Share this post


Link to post
Share on other sites
ScootA    270
Distance between a line and a point is defined as:

d = (| b x (p-a) |) / |b|

Where p is a vector containing the point, a is the origin of the line, and b is the vector of the line. Ill let you put that into code...

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this