Determining if two lines intersect

Today we are going to take a look at intersecting lines. There are some information on this scattered around the internet, but a good example is hard to find. The uses for this is mainly in 2D, it can be applied to lighting, physics and all other applications using rays.

Intersecting and non-intersecting lines

To solve this, we want to convert our lines to the following form:

This allows us to create an equation that we can solve, with no need for ray tracing or other techniques. Converting our lines to this form is pretty trivial, as shown below. We do this for both lines, giving us the equations for both.

Now when we have the expression for both lines, first of all we want to find the determinant to check if the lines are exactly parallel (they never intersect). The lines are parallel if the determinant is equal to zero.
We find the determinant this by solving the following expression:

If the determinant is equal to zero, then the lines are perfectly parallel and will never intersect. If the lines are not parallel however, we know that they must intersect at some point. The point which the lines intersects are found using the formula below.

If we want to check if the intersection happened on our lines(limited by their length), we can simply check if the intersection point is between the end points of both lines like this:

The math might look a bit alien, but for all you programmers out there; here is all the code needed for checking if two lines intersect. Please note that the implementation of the Line class already generates the correct expression for the lines. The code for this class is appended below.