mattlundstrom
7/13/2012 - 7:47 PM

Intersection between 2 lines

Intersection between 2 lines

public static function getLineIntersection (a1:Point,a2:Point,b1:Point,b2:Point):Point{    //calculate directional constants    var 

k1:Number = (a2.y-a1.y) / (a2.x-a1.x);    var k2:Number = (b2.y-b1.y) / (b2.x-b1.x);

    // if the directional constants are equal, the lines are parallel,    // meaning there is no intersection point.    if( k1 == k2 ) 

return null;
    var x:Number,y:Number;    var m1:Number,m2:Number;
    // an infinite directional constant means the line is vertical    if( !isFinite(k1) ) {
    // so the intersection must be at the x coordinate of the line    x = a1.x;    m2 = b1.y - k2 * b1.x;    y = k2 * x + m2;
    // same as above for line 2    } else if ( !isFinite(k2) ) {
    m1 = a1.y - k1 * a1.x;    x = b1.x;    y = k1 * x + m1;
    // if neither of the lines are vertical    } else {
    m1 = a1.y - k1 * a1.x;    m2 = b1.y - k2 * b1.x;    x = (m1-m2) / (k2-k1);    y = k1 * x + m1;
  }
 return new Point(x,y);
}