Skip to content

Instantly share code, notes, and snippets.

@percentjuice
Forked from painquin/lineintersection.as
Last active August 29, 2015 14:06
Show Gist options
  • Save percentjuice/fec82bb7af5b71a691b5 to your computer and use it in GitHub Desktop.
Save percentjuice/fec82bb7af5b71a691b5 to your computer and use it in GitHub Desktop.
// ported from http://alienryderflex.com/intersect/
public static function LineIntersection(a:Point, b:Point, c:Point, d:Point):Point
{
var distAB:Number, cos:Number, sin:Number, newX:Number, ABpos:Number;
if ((a.x == b.x && a.y == b.y) || (c.x == d.x && c.y == d.y)) return null;
if ( a == c || a == d || b == c || b == d ) return null;
b = b.clone();
c = c.clone();
d = d.clone();
b.offset( -a.x, -a.y);
c.offset( -a.x, -a.y);
d.offset( -a.x, -a.y);
// a is now considered to be (0,0)
distAB = b.length;
cos = b.x / distAB;
sin = b.y / distAB;
c = new Point(c.x * cos + c.y * sin, c.y * cos - c.x * sin);
d = new Point(d.x * cos + d.y * sin, d.y * cos - d.x * sin);
if ((c.y < 0 && d.y < 0) || (c.y >= 0 && d.y >= 0)) return null;
ABpos = d.x + (c.x - d.x) * d.y / (d.y - c.y); // what.
if (ABpos < 0 || ABpos > distAB) return null;
return new Point(a.x + ABpos * cos, a.y + ABpos * sin);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment