Simple Line Collision Detection

point line Simple Line Collision DetectionLine 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:

y = mx + b
m = y1 – y2
x1 – x2

 

 

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:

x = a
y = b

 

 
lines Simple Line Collision DetectionIn 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:

x =  b2 – b1
m1- m2
y = m1x + b1
y = m2x + b2

 

 

 
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.

flag1 = false;
flag2 = false;

if((Px >= L1x1 AND Px <= L1x2) OR (Px <= L1x1 AND Px >= L1x2) OR
(Py >= L1y1 AND Py <= L1y2) OR (Py <= L1y1 AND Py >= L1y2)){
flag1 = true;
}

if((Px >= L2x1 AND Px <= L2x2) OR (Px <= L2x1 AND Px >= L2x2) OR
(Py >= L2y1 AND Py <= L2y2) OR (Py <= L2y1 AND Py >= L2y2)){
flag2 = true;
}

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

// The lines are colliding
}
else{
// The lines aren’t colliding
}

You may also like...