# Distance between two lines in 3D

Assume you have two parametric lines: $p_1=r_1+e_1$ and $p_2=r_2+e_2$

Start by analyzing if they are parallel, by checking the if the normalized directions vectors ($e$) are identical. If they are, pick any point on $p_1$, and run the point-to-line formula (google it).

Otherwise, continue as follows:
The definition of ‘distance’ is the minimum distance between any two points A,B on the two lines. So assume points A,B are the ones who provide the minimum distance between the lines.

Now, the line AB must be perpendicular to both lines $p_1,p_2$. Why? Because otherwise you can move a bit on one of the lines to make the distance shorter. If you move $\epsilon$, the distance will be reduced by $\epsilon \cdot cos(\alpha)$, where $\alpha \neq 90 deg$

So the only vector direction which is perpendicular to both lines is $n=e_1 \times e_2$. This is by definition of cross product. Let’s define $\hat{n}$ as its normalized version. Great.

Now imagine that we place the coordinates origin at point B. Since $AB$ is perpendicular to any point $p_1$ and specifically to point $r_1$, we have a right angled triangle $r_1AB$, and the distance $|AB|=d$ is

$d=\hat{n} \cdot (r_1-B) $

Great now let’s write B as $B=r_2 + (B-r_2)$ and we get:

$d=\hat{n} \cdot (r_1-r_2-(B-r_2))$

Now, we know that the vector $B-r_2$ in perpendicular to $\hat{n}$, by definition, so its dot product is zero. Therefore:

\(d=\hat{n} \cdot (r_1 - r_2) \: \: \square\)