Given two parametric equations of lines;
L=a+t.b // t is the paramerter, a & b are vectors
M=c+u.d //u is parameter, c & d are vectors
The the point of intersection is the one place in space where both these equations are equal(produce the same point). When the lines intersect at some value of t and some value of u, the equations are equal, because they resolve to the same point;
L=M
a+tb=c+u.d
Now we have an equation with two unknowns (u & t). In order to find the point of intersection we need at least one of the unknowns. First step is to isolate one of the unknowns, in this case t
;
t=(c+u.d-a)/b
but this is a 2D Vector equation, so it is really two equations, one in x and the other in y. Two equations is (usually) enough to solve a system with two unknowns.
t=(cx+u.dx-ax)/bx
t=(cy+u.dy-ay)/by
So now we have two expressions, which equal the same value (t
), so they must equal each other. That is why we isolated t, in order to have two equations which equal each other AND only one unknown on either side.
(cx+u.dx-ax)/bx = t = (cy+u.dy-ay)/by //from above
// equate and isolate u
(cx+u.dx-ax)/bx=(cy+udy-ay)/by //note: `t` is gone
Now, we have an equation with only one unknown, which we will solve by isolating the remaining unknown, u
cx.by+u.dx.by-ax.by=cy.bx+u.dy.bx-ay.bx
u.dx.by-u.dy.bx=cy.bx-ay.bx-cx.by+ax.by
//result
u=(cy.bx-ay.bx-cx.by+ax.by)/(dx.by-dy.bx)
u=(bx(cy-ay) +by(ax-cx))/(dx.by-dy.bx) //tidied up slightly
Calculating u and putting it back into M=c+u.d
will give you the point of intersection of the two lines.
of course you will need to check if 0<=u<=1
to see if the line segment intersects
Note that you cannot use this value of u
in the equation L=a+t.b
, you have to use a different but similar equation to calculate t
and check if 0<=t<=1
.
//derived in a similar fashion to u
t=(dx(ay-cy) +dy(cx-ax))/(bx.dy-by.dx) //tidied up slightly
u
& t
will have different values for the same intersection point, but if both are between 0 & 1 the the two line segments intersect.
Note that if (dx.by-dy.bx)
is zero, then the lines are parallel and never intersect.
By the way, if you only have the start and end points of the line segments, you can still use these equations, using the following conversions.
s1x,s1y // start point of line 1
e1x,e1y // end point of line 1
s2x,s2y // start point of line 2
e2x,e2y // end point of line 2
ax=s1x
ay=s1y
bx=e1x-s1x
by=e1y-s1y
cx=s2x
cy=s2y
dx=e2x-s2x
dy=e2y-s2y