Checks two lines for intersection - CSharp System

CSharp examples for System:Math Geometry

Description

Checks two lines for intersection

Demo Code


using System.Windows;
using System;//from   w  ww. j av  a  2 s. c o m

public class Main{
        /// <summary>
        /// Checks two lines for intersection
        /// </summary>
        /// <param name="firstLineStart">The first line start.</param>
        /// <param name="firstLineEnd">The first line end.</param>
        /// <param name="secondLineStart">The second line start.</param>
        /// <param name="secondLineEnd">The second line end.</param>
        /// <returns>The intersection check result. Null means no intersection</returns>
        public static Point? GetLineIntersection(Point firstLineStart, Point firstLineEnd, Point secondLineStart, Point secondLineEnd)
        {
            var b = firstLineEnd - firstLineStart;
            var d = secondLineEnd - secondLineStart;
            var delta = (b.X * d.Y) - (b.Y * d.X);
            var c = secondLineStart - firstLineStart;
            var t = ((c.X * d.Y) - (c.Y * d.X)) / delta;
            if (double.IsNaN(t) || t < 0 || t > 1)
            {
                return null;
            }

            var u = ((c.X * b.Y) - (c.Y * b.X)) / delta;
            if (double.IsNaN(u) || u < 0 || u > 1)
            {
                return null;
            }

            return firstLineStart + (t * b);
        }
}

Related Tutorials