/// <summary> /// Determines the shortest distance from this point to the specified line segment. /// </summary> /// <param name="line">The line segment.</param> /// <param name="sign">-1 if the point resides above the line, or 1 if the point resides below the line.</param> /// <returns></returns> public double DistanceTo(LineSeg2D line, out int sign) { double dist = CrossProduct(line.Start, line.End, this) / Delta(line.Start, line.End); if (dist < 0) { sign = -1; } else { sign = 1; } return(Math.Abs(dist)); }
/// <summary> /// Determines the point of intersection between the specified lines. /// </summary> /// <param name="line1">Line 1.</param> /// <param name="line2">Line 2.</param> /// <returns>The point of intersection if the lines intersect; otherwise, null.</returns> public static Point2D IntersectAt(LineSeg2D line1, LineSeg2D line2) { // Denominator for ua and ub are the same, so store this calculation double d = (line2.Y2 - line2.Y1) * (line1.X2 - line1.X1) - (line2.X2 - line2.X1) * (line1.Y2 - line1.Y1); //n_a and n_b are calculated as seperate values for readability double n_a = (line2.X2 - line2.X1) * (line1.Y1 - line2.Y1) - (line2.Y2 - line2.Y1) * (line1.X1 - line2.X1); double n_b = (line1.X2 - line1.X1) * (line1.Y1 - line2.Y1) - (line1.Y2 - line1.Y1) * (line1.X1 - line2.X1); // Make sure there is not a division by zero - this also indicates that // the lines are parallel. if (d == 0) { return(null); } // Calculate the intermediate fractional point that the lines potentially intersect. double ua = n_a / d; double ub = n_b / d; Point2D intersection = null; if (ua >= 0d && ua <= 1d && ub >= 0d && ub <= 1d) { intersection = new Point2D(); intersection.X = line1.X1 + (ua * (line1.X2 - line1.X1)); intersection.Y = line1.Y1 + (ua * (line1.Y2 - line1.Y1)); } return(intersection); }
/// <summary> /// Determines the angle between line 1 and line 2. /// </summary> /// <param name="line1">Line 1.</param> /// <param name="line2">Line 2.</param> /// <returns></returns> public static double AngleBetween(LineSeg2D line1, LineSeg2D line2) { return(System.Math.Atan2(line1.Y2 - line1.Y1, line1.X2 - line1.X1) - System.Math.Atan2(line2.Y2 - line2.Y1, line2.X2 - line2.X1)); }
/// <summary> /// Determines the shortest distance from this point to the specified line segment. /// </summary> /// <param name="line">The line segment.</param> /// <returns></returns> public double DistanceTo(LineSeg2D line) { double dist = CrossProduct(line.Start, line.End, this) / Delta(line.Start, line.End); return(Math.Abs(dist)); }