Ejemplo n.º 1
0
        /// <summary>
        /// Finds the shortest distance between two line segments.
        /// </summary>
        /// <param name="lineSegment"></param>
        /// <param name="otherLineSegment"></param>
        /// <param name="shortestDistanceSegment">Outputs a line segment for the shortest found distance.
        /// PointA is on the first input line segment, PointB is on the second input line segment. </param>
        /// <returns></returns>
        public static double ShortestSquaredDistanceToOtherLineSegment(this LineSegment2D lineSegment, LineSegment2D otherLineSegment, out LineSegment2D shortestDistanceSegment)
        {
            Point2D?intersectionPoint;

            if (lineSegment.IntersectsOtherLineSegment(otherLineSegment, out intersectionPoint))
            {
                shortestDistanceSegment = new LineSegment2D(intersectionPoint.Value, intersectionPoint.Value);
                return(0);
            }

            Point2D pointA, pointB;
            double  shortestSquaredDistance;

            // Check first end point on first segment to second line segment.
            pointA = lineSegment.PointA;
            shortestSquaredDistance = otherLineSegment.ShortestSquaredDistanceToPoint(lineSegment.PointA, out pointB);

            Point2D pointCandidate;
            double  distanceCandidate;

            // Check second end point on first segment to second line segment.
            distanceCandidate = otherLineSegment.ShortestSquaredDistanceToPoint(lineSegment.PointB, out pointCandidate);
            if (distanceCandidate < shortestSquaredDistance)
            {
                shortestSquaredDistance = distanceCandidate;
                pointA = lineSegment.PointB;
                pointB = pointCandidate;
            }

            // Check first end point on second line segment to first line segment.
            distanceCandidate = lineSegment.ShortestSquaredDistanceToPoint(otherLineSegment.PointA, out pointCandidate);
            if (distanceCandidate < shortestSquaredDistance)
            {
                shortestSquaredDistance = distanceCandidate;
                pointA = pointCandidate;
                pointB = otherLineSegment.PointA;
            }

            // Check second end point on second line segment to first line segment.
            distanceCandidate = lineSegment.ShortestSquaredDistanceToPoint(otherLineSegment.PointB, out pointCandidate);
            if (distanceCandidate < shortestSquaredDistance)
            {
                shortestSquaredDistance = distanceCandidate;
                pointA = pointCandidate;
                pointB = otherLineSegment.PointB;
            }

            shortestDistanceSegment = new LineSegment2D(pointA, pointB);
            return(shortestSquaredDistance);
        }