crossing lines in AS3
Trying to see if two lines connect or not?
Here's a little class (just barely) I wrote to aid with a little personal project
the idea is that you treat both lines as functions and equate them to one another.
Pa + fa * (Pb - Pa) = Pc + fb * (Pd - Pc);
Each point is made of x and y, so you separate the equation by substituting each point by x and then y; You can then solve for fa and fb;
It is important to solve for both fa and fb because the in both cases you are treating the intersecting line as infinite. (of course, this could be useful in some applications)
If the resulting numbers fall within 0 and 1, they intersect. if the number is infinity, they are parallel. In my code, I'm excluding when this number is 0 or 1. These are the end points, and I don't consider that as crossing.
package
{
import flash.geom.Point;
/**
* ...
* @author Daniel Poda / 2008
*/
package
{
import flash.geom.Point;
/**
* ...
* @author Daniel Poda / 2008
*/
public class pointUtils
{
public function getIntersectingPointF($A:Point, $B:Point, $C:Point, $D:Point):Number {
var A:Point = $A.clone();
var B:Point = $B.clone();
var C:Point = $C.clone();
var D:Point = $D.clone();
var f_ab:Number = (D.x - C.x) * (A.y - C.y) - (D.y - C.y) * (A.x - C.x);
// are lines parallel
if (f_ab == 0) { return Infinity };
var f_cd:Number = (B.x - A.x) * (A.y - C.y) - (B.y - A.y) * (A.x - C.x);
var f_d:Number = (D.y - C.y) * (B.x - A.x) - (D.x - C.x) * (B.y - A.y);
var f1:Number = f_ab/f_d
var f2:Number = f_cd / f_d
if (f1 == Infinity || f1 <= 0 || f1 >= 1) { return Infinity };
if (f2 == Infinity || f2 <= 0 || f2 >= 1) { return Infinity };
return f1;
}
public function getIntersectingPoint($A:Point, $B:Point, $C:Point, $D:Point):Point
{
var f:Number = getIntersectingPointF($A, $B, $C, $D);
if (f == Infinity || f <= 0 || f >= 1) { return null };
var retPoint:Point = Point.interpolate($A, $B, 1 - f);
return retPoint.clone();
}
}
}