Exemple #1
0
        // https://stackoverflow.com/a/565282/3333753
        static public bool Intersects(this Segment segmentA, Segment segmentB, out Segment?intersection)
        {
            Vector2 vectorA = segmentA.Vector;
            Vector2 vectorB = segmentB.Vector;

            Vector2 p0Diff = segmentB.P0 - segmentA.P0;
            float   b      = p0Diff.Cross(vectorB);

            float abCross = vectorA.Cross(vectorB);

            // Check if segments are parallel
            if (abCross.EqualsZero())
            {
                // Check if segments are colinear
                if (b.EqualsZero())
                {
                    float         aaDot = Vector2.Dot(vectorA, vectorA);
                    float         baDot = Vector2.Dot(vectorB, vectorA);
                    float         t0    = Vector2.Dot(p0Diff, vectorA) / aaDot;
                    float         t1    = t0 + baDot / aaDot;
                    Range <float> t01   = baDot >= 0 ? new Range <float>(t0, t1) : new Range <float>(t1, t0);

                    // Check if segments are overlapping
                    if (RangeUtils.Intersects(t01, new Range <float>(0, 1)))
                    {
                        intersection = new Segment(segmentA.P0 + t01.Min * vectorA, segmentA.P0 + t01.Max * vectorA);
                        return(true);
                    }
                }
            }
            else
            {
                float a = p0Diff.Cross(vectorA);

                float t = a / abCross;
                float u = b / abCross;

                // Check if intersect at one point
                if (t >= 0 && t <= 1 && u >= 0 && u <= 1)
                {
                    Vector2 intersectionPoint = segmentA.P0 + t * vectorA;
                    intersection = new Segment(intersectionPoint, intersectionPoint);
                    return(true);
                }
            }

            intersection = null;
            return(false);
        }