Tag Archives: Graphic Gems

Faster Line Segment Intersection for Unity3D/C#

This method tests whether two lines are intersecting each other. The code is based on the algorithm described by

Faster Line Segment Intersection
Franklin Antonio, Graphics Gems III, 1992, pp. 199-202
ISBN: 0-12-409673-5

The implementation tests only the intersection and will not calculate any possible intersection point.

static bool FasterLineSegmentIntersection(Vector2 p1, Vector2 p2, Vector2 p3, Vector2 p4) {
 
    Vector2 a = p2 - p1;
    Vector2 b = p3 - p4;
    Vector2 c = p1 - p3;
 
    float alphaNumerator = b.y*c.x - b.x*c.y;
    float alphaDenominator = a.y*b.x - a.x*b.y;
    float betaNumerator  = a.x*c.y - a.y*c.x;
    float betaDenominator  = alphaDenominator; /*2013/07/05, fix by Deniz*/
 
    bool doIntersect = true;
 
    if (alphaDenominator == 0 || betaDenominator == 0) {
        doIntersect = false;
    } else {
 
        if (alphaDenominator > 0) {
            if (alphaNumerator < 0 || alphaNumerator > alphaDenominator) {
                doIntersect = false;
            }
        } else if (alphaNumerator > 0 || alphaNumerator < alphaDenominator) {
            doIntersect = false;
        }
 
        if (doIntersect && betaDenominator > 0) {
            if (betaNumerator < 0 || betaNumerator > betaDenominator) {
                doIntersect = false;
            }
        } else if (betaNumerator > 0 || betaNumerator < betaDenominator) {
            doIntersect = false;
        }
    }
 
    return doIntersect;
}