Sunday 27 January 2013

Simple Line Collision Detection

It might not be obvious at first, but Line Intersections are actually very handy.
For example, you can use them to define complex polygon shapes (octagons, stars, etc) and from there calculate the collision between them!

But in order to determine where the lines collide with each other, we first need the equation of a straight line:

y = m x + b
m =  y1 - y2  
        x1 - x2




So to determine any given point of a line we need to know its slope (m) and its y-intercept (b). Then all we need to do is give a X coordinate to obtain the corresponding Y coordinate of the point.

As for determining if a point belongs to a line, all we need to do is to use the point's X coordinate and check if the resulting Y matches the point's.

There are 2 exceptions we have to keep in mind however, vertical and horizontal lines. These follow special equations, where b is a constant value:

x = b
y = b



Now unless 2 lines have the same slope (which makes them parallel), they will intersect at some point, even if it's far off in space.
So the first thing we need is the equation of both lines. Each has its own slope and y-intercept, but because we're trying to find the point they have in common, the X and Y coordinate is the same for both:

y = m1 x + b1
y = m2 x + b2




From there all we need to do is to replace the Y to make the equations equal to each other and find the X value. Then we just need to replace the X value in either of the equations to get the Y, like in this example.
Just in case it's ever needed, this is how the equation solved to X looks like (it doesn't work for vertical or horizontal lines though):

 x =   b2 - b1  
        m1 - m2




Now there's only one thing missing. The equations we've used so far stretch into infinity, but what happens when we're dealing with line segments?
The computer would say the red and green lines are colliding, even though we can see the green line ends before it touches the red one.

So once we have the intersection point, we need to find out if it's within the boundaries of both segments:


flag_line1 = false
flag_line2 = 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 ) ) {

     flag_line1 = 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 ) ) {

     flag_line2 = true
}

if (flag_line1 == true AND flag_line2 == true ) {

      // The line segments collide
}

0 comments:

Post a Comment

 

Break-a-Loop Copyright © 2013 | Template design by O Pregador | Powered by Blogger Templates