# 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.

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.

Source: Line.cs

## Comments

## Ilija Soskic

on Jun 02, 2016Reply

This was 3 years ago, and I find this so useful. Thank you so much. I’ll be implementing this in “Last Bullet” on GameJolt. Thank you again so much for this simple and easy eplanation!

## Nex

on Jul 24, 2016Reply

I’m very happy that you found it useful!

## Leave a comment