Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- namespace DistanceTask
- {
- public static class DistanceTask
- {
- public static double K, M, Intersection_X, Intersection_Y;
- // Расстояние от точки (x, y) до отрезка AB с координатами A(ax, ay), B(bx, by)
- public static double GetDistanceToSegment(double ax, double ay, double bx, double by, double x, double y)
- {
- if (ax - bx != 0) return SegmentIsVertical(ref ax, ref ay, ref bx, ref by, ref x, ref y);
- else return SegmentIsNotVertical(ref ax, ref ay, ref bx, ref by, ref x, ref y);
- }
- public static double SegmentIsVertical(ref double ax, ref double ay,
- ref double bx, ref double by,
- ref double x, ref double y)
- {
- K = (ay - by) / (ax - bx);
- M = ay - K * ax;
- Intersection_Y = (M + K * K * y + K * x) / (1 + K * K);
- if (K != 0) Intersection_X = (Intersection_Y - M) / K;
- else Intersection_X = x;
- if ((x == ax && y == ay) ||
- (x == bx && y == by) ||
- (y == K * x + M && ((x >= ax && x <= bx) || (x >= bx && x <= ax))))
- return 0.0;
- else if ((Intersection_X >= ax && Intersection_X <= bx) ||
- (Intersection_X <= ax && Intersection_X >= bx))
- return Math.Sqrt((x - Intersection_X) * (x - Intersection_X) +
- (y - Intersection_Y) * (y - Intersection_Y));
- return FindTheMinimumDistance(ref ax, ref ay, ref bx, ref by, ref x, ref y);
- }
- public static double SegmentIsNotVertical(ref double ax, ref double ay,
- ref double bx, ref double by,
- ref double x, ref double y)
- {
- Intersection_Y = y;
- Intersection_X = ax;
- if ((Intersection_Y >= ay && Intersection_Y <= by) ||
- (Intersection_Y <= ay && Intersection_Y >= by))
- return Math.Sqrt((x - Intersection_X) * (x - Intersection_X) +
- (y - Intersection_Y) * (y - Intersection_Y));
- else if (x == ax && ((y >= ay && y <= by) ||
- (y >= by && y <= ay)))
- return 0.0;
- return FindTheMinimumDistance(ref ax, ref ay, ref bx, ref by, ref x, ref y);
- }
- public static double FindTheMinimumDistance(ref double ax, ref double ay,
- ref double bx, ref double by,
- ref double x, ref double y)
- {
- return Math.Min(
- Math.Sqrt( (x - ax) * (x - ax) + (y - ay) * (y - ay) ),
- Math.Sqrt( (x - bx) * (x - bx) + (y - by) * (y - by) )
- );
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement