31-03-2008, 07:35 AM
Hello,
the following code snippet contains a method for calculating the intersection point of two lines.
Based on a solution in C by Darel Rex Finley
cheers
the following code snippet contains a method for calculating the intersection point of two lines.
Based on a solution in C by Darel Rex Finley
cheers
Code:
/*
* adapted from Darel Rex Finley, 2006: http://alienryderflex.com/intersect/
*
* Determines the intersection point of the line defined by points A and B
* with the line defined by points C and D.
*
* */
private function _lineIntersection(ax:Number, ay:Number,bx:Number, by:Number,cx:Number, cy:Number,dx:Number, dy:Number):Point {
var distAB:Number;
var theCos:Number;
var theSin:Number;
var newX:Number;
var posAB:Number ;
// Fail if either line segment is zero-length.
if (ax==bx && ay==by || cx==dx && cy==dy) return null;
// (1) Translate the system so that point A is on the origin.
bx-=ax; by-=ay;
cx-=ax; cy-=ay;
dx-=ax; dy-=ay;
// Discover the length of segment A-B.
distAB=Math.sqrt(bx*bx+by*by);
// (2) Rotate the system so that point B is on the positive X axis.
theCos = bx / distAB;
theSin = by / distAB;
newX = cx * theCos + cy * theSin;
cy = cy * theCos - cx * theSin; cx = newX;
newX = dx * theCos + dy * theSin;
dy = dy * theCos - dx * theSin; dx = newX;
// Fail if the lines are paralles
if (cy == dy) return null;
// (3) Discover the position of the intersection point along line A-B.
posAB=dx+(cx-dx)*dy/(dy-cy);
// (4) Apply the discovered position to line A-B in the original coordinate system.
return new Point(ax + posAB * theCos, ay + posAB * theSin);
}