//------------------------- DistToLineSegment ---------------------------- // // given a line segment AB and a point P, this function calculates the // perpendicular distance between them //------------------------------------------------------------------------ public static double DistToLineSegment(Vector2D A, Vector2D B, Vector2D P) { //if the angle is obtuse between PA and AB is obtuse then the closest //vertex must be A double dotA = (P.X - A.X) * (B.X - A.X) + (P.Y - A.Y) * (B.Y - A.Y); if (dotA <= 0) { return(Vector2D.Vec2DDistance(A, P)); } //if the angle is obtuse between PB and AB is obtuse then the closest //vertex must be B double dotB = (P.X - B.X) * (A.X - B.X) + (P.Y - B.Y) * (A.Y - B.Y); if (dotB <= 0) { return(Vector2D.Vec2DDistance(B, P)); } //calculate the point along AB that is the closest to P Vector2D Point = A + ((B - A) * dotA) / (dotA + dotB); //calculate the distance P-Point return(Vector2D.Vec2DDistance(P, Point)); }
//-------------------- LineIntersection2D------------------------- // // Given 2 lines in 2D space AB, CD this returns true if an // intersection occurs and sets dist to the distance the intersection // occurs along AB. Also sets the 2d vector point to the point of // intersection //----------------------------------------------------------------- public static bool LineIntersection2D(Vector2D A, Vector2D B, Vector2D C, Vector2D D, ref double dist, ref Vector2D point) { double rTop = (A.Y - C.Y) * (D.X - C.X) - (A.X - C.X) * (D.Y - C.Y); double rBot = (B.X - A.X) * (D.Y - C.Y) - (B.Y - A.Y) * (D.X - C.X); double sTop = (A.Y - C.Y) * (B.X - A.X) - (A.X - C.X) * (B.Y - A.Y); double sBot = (B.X - A.X) * (D.Y - C.Y) - (B.Y - A.Y) * (D.X - C.X); if ((rBot == 0) || (sBot == 0)) { //lines are parallel return(false); } double r = rTop / rBot; double s = sTop / sBot; if ((r > 0) && (r < 1) && (s > 0) && (s < 1)) { dist = Vector2D.Vec2DDistance(A, B) * r; point = A + (B - A) * r; return(true); } else { dist = 0; return(false); } }
//--------------------LineIntersection2D------------------------- // // Given 2 lines in 2D space AB, CD this returns true if an // intersection occurs and sets dist to the distance the intersection // occurs along AB // //----------------------------------------------------------------- public static bool LineIntersection2D(Vector2D A, Vector2D B, Vector2D C, Vector2D D, ref double dist) { double rTop = (A.Y - C.Y) * (D.X - C.X) - (A.X - C.X) * (D.Y - C.Y); double sTop = (A.Y - C.Y) * (B.X - A.X) - (A.X - C.X) * (B.Y - A.Y); double Bot = (B.X - A.X) * (D.Y - C.Y) - (B.Y - A.Y) * (D.X - C.X); if (Bot == 0)//parallel { if (isEqual(rTop, 0) && isEqual(sTop, 0)) { return(true); } return(false); } double r = rTop / Bot; double s = sTop / Bot; if ((r > 0) && (r < 1) && (s > 0) && (s < 1)) { dist = Vector2D.Vec2DDistance(A, B) * r; return(true); } else { dist = 0; return(false); } }