# Distance from infinite line to point

## Recommended Posts

I have: length (distance), dir (normalized), PA (pos), PB (pos), X (pos, grey "+" on the image) I want: DR (distance) What would be the most efficient way to obtain the DR distance? I've been calculating it like this..
float DL = Dot( dir, X - PA );
Vector IntersectPoint = PA + dir*DL;
float DR = (IntersectPoint - X).Length();
But I'm hoping there's a simpler and more efficient approach to this? Help is appreciated.

##### Share on other sites
Your method is not too bad. An alternative is to use the Pythagorean theorem this way:

float distance(Point &X, Line &L){  Vector AX = X - L.A;  float DL = Dot(L.dir,AX);  return sqrt(Dot(AX,AX) - DL*DL);}

The performance killer in either case is the square root, just as with computing the distance between two points. In many cases you can get away with just computing the square of the distance.

##### Share on other sites
Optimizing this is fairly pointless, to get any actual performance increase you need far more context then this, preferable the surrounding loop that it can be inlined into for better instruction scheduling, etc...

However, the easiest to understand / most logical way IMO is to project x into the line then get the component perpendicular to the line by subtracting this from x and finally take the length of the result, assuming d = dir is unit length then
Proj_d(x) = <x, d> * dOrtho_d(x) = x - Proj_d(x) = x - <x, d> * ddist = |x - <x, d> * d|