public static Segment NearestEdgeFromPointToPolygon(Point P, ConvexPolygon polygon) { double distance = double.PositiveInfinity; Segment nearest = null; for (int i = 0; i < polygon.Count; i++) { Point A = polygon[i]; Point B = polygon[(i + 1) % polygon.Count]; double curDistance = P.DistanceToSegment(new Segment(A, B)); if (curDistance < distance) { distance = curDistance; nearest = new Segment(A, B); } distance = Math.Min(distance, P.DistanceToSegment(new Segment(A, B))); } return(nearest); }