[Math] Given two parallel line segments, how to tell if and where they overlap

geometry

To find if two line segments intersect I am this code

The problem is this code:

// if abs(angle)==1 then the lines are parallell,  
// so no intersection is possible  
if(abs(deg)==1) return null;

At that point we know that the lines are parallel, but we don't know if they overlap and where.

If I have a line segment 5,5 to 10,10 and another line segment 7,7 to 12,12 then I'd like to determine that the line segment 7,7 to 10,10 is the overlap.

Best Answer

This method will work for all lines in any dimension.

Parametrize your line using the vector equation of a line:

$\textbf{r} = t\textbf{s} + \textbf{c}$

Then the $t$ values of the two line segments (assuming they do intersect) will correspond to certain intervals. The overlap will correspond to the $t$ values of the intersection of these intervals.

For your example the line is parametrized by:

$\textbf{r} = t\binom{1}{1}$

The first line segment corresponds to $t$ values in the interval $[5,10]$ and the second to $[7,12]$. Thus the overlap corresponds to points with $t$ value in $[7,10]$, i.e. the line segment joining $(7,7)$ to $(10,10)$.