Friday, 27 June 2014

Algorithm I: Line-Line Intersection

The following tutorial will explain how to detect line-line intersections in 2D space. This is a very common task and is used in many different situations (especially in video games).

1
2
3
4
5
6
7
8
public Vector3 ABCLineEquation(Vector2 pointA, Vector2 pointB)
{
 float A = pointB.y - pointA.y;
 float B = pointA.x - pointB.x;
 float C = (A * pointA.x) + (B * pointA.y);

 return new Vector3 (A, B, C);
}

To start with we need this little method to return the line equation of a line between two points (A and B). In this case the method is taking two 2D vectors as the two points (a 2D vector has an x and a y component).

An ABC line equation is similar to the common y = mx + c equations, but takes the form Ay + Bx + C = 0. This particular form is generally more useful in programming applications, as it can cut down a lot of calculations that would be needed for the more common form (it tells use the coefficients of the x and y values, which the y = mx + c equation does not. We use the common form of line equation when doing maths in our head because we can use inspection, which a computer cannot do).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
public Vector2 IntersectionOfTwoLines (Vector2 pointA1, Vector2 pointB1, Vector2 pointA2, Vector2 pointB2)
{
 Vector3 lineA = ABCLineEquation (pointA1, pointB1);
 Vector3 lineB = ABCLineEquation (pointA2, pointB2);

 float determinant = (lineA.x * lineB.y) - (lineB.x * lineA.y);

 if(determinant == 0f)
 {
  return new Vector2.zero;
 }
  
 float x = (lineB.y * lineA.z - lineA.y * lineB.z) / determinant;
 float y = (lineA.x * lineB.z - lineB.x * lineA.z) / determinant;
  
 Vector2 intersection = new Vector2(x, y);
  
 return intersection;
}

This second method is doing the bulk of the work. It takes 4 points, with points A and B forming a line for sets 1 and 2 (i.e A1 -> B1 is one line, A2 -> B2 is another). The first thing needed is to get the ABC line equation of the two lines (stored as a 3D vector here).

Next the determinant is calculated. The determinant is useful in that it can tell us about the intersections of the two lines. If the determinant is equal to zero, then the two lines are parallel, and so there is no intersection between them. In my method I have set it to return a zero Vector2 (0,0) if the lines are parallel. If the determinant is not zero, then the lines do intersect (huzzah!).

Now it's only a couple of simple calculations using the ABC values of the two lines to work out the x and y values of the intersection. Finally I create a Vector2, just like the input value types, and set the x & y values accordingly before returning it.

That's it! Hopefully this was useful and readable for you. Thanks!

No comments:

Post a Comment