# Simple Line Collision Detection

Line collisions are pretty powerful, since you can define pretty much any shape through lines. But at the same time they can be rather tricky, since they require to know a few equations about their properties.

So lets start with the Point-Line collision. First of all we need to know the equation of the line:

_{1}– y

_{2}

x

_{1}– x

_{2}

As long as we have the slope (m) and the y-intercept (b) we can put in the X coordinate of the point and see if it intersects with the line or not.

But there are 2 exceptions to the line equation, when the line is vertical (m = ∞) or horizontal (m = 0). In those circumstances it these are used instead, where **a** is the x-intercept and **b** the y-intercept:

In the Line-Line collision unless they have the same slope, making them parallel, they will intersect one another, even if somewhere far off in space.

Since the intersection is the point where both lines have the same coordinates, we just need to take the equations of both lines and solve them for X in order to later find the Y:

_{2}– b

_{1}

m

_{1}- m

_{2}

_{1}x + b

_{1}

y = m

_{2}x + b

_{2}

Though keep in mind that equation for X only applies for non-vertical or horizontal lines. In case we’re dealing with those we just need to place the X or Y in the other line equation and find the other coordinate directly.

But what if we’re dealing with line segments and not with lines that stretch into infinity?

After finding the intersection point we then need to check if it’s within the limits of both lines. If it’s not then the lines aren’t intersecting.

flag2 = false;

if((P_{x} >= L1_{x1} AND P_{x} <= L1_{x2}) OR (P_{x} <= L1_{x1} AND P_{x} >= L1_{x2}) OR

(P_{y} >= L1_{y1} AND P_{y} <= L1_{y2}) OR (P_{y} <= L1_{y1} AND P_{y} >= L1_{y2})){

flag1 = true;

}

if((P_{x} >= L2_{x1} AND P_{x} <= L2_{x2}) OR (P_{x} <= L2_{x1} AND P_{x} >= L2_{x2}) OR

(P_{y} >= L2_{y1} AND P_{y} <= L2_{y2}) OR (P_{y} <= L2_{y1} AND P_{y} >= L2_{y2})){

flag2 = true;

}

if(flag1 == true AND flag2 == true){

// The lines are colliding

}

else{

// The lines aren’t colliding

}