public static double distanceSq ( LineSegment2D_F64 segmentA , LineSegment2D_F64 segmentB ) { // intersection of the two lines relative to A double slopeAX = segmentA . slopeX ( ) ; double slopeAY = segmentA . slopeY ( ) ; double slopeBX = segmentB . slopeX ( ) ; double slopeBY = segmentB . slopeY ( ) ; double ta = slopeBX * ( segmentA . a . y - segmentB . a . y ) - slopeBY * ( segmentA . a . x - segmentB . a . x ) ; double bottom = slopeBY * slopeAX - slopeAY * slopeBX ; // see they intersect if ( bottom != 0 ) { // see if the intersection is inside of lineA ta /= bottom ; if ( ta >= 0 && ta <= 1.0 ) { // see if the intersection is inside of lineB double tb = slopeAX * ( segmentB . a . y - segmentA . a . y ) - slopeAY * ( segmentB . a . x - segmentA . a . x ) ; tb /= slopeAY * slopeBX - slopeBY * slopeAX ; if ( tb >= 0 && tb <= 1.0 ) return 0 ; } } double closest = Double . MAX_VALUE ; closest = Math . min ( closest , distanceSq ( segmentA , segmentB . a ) ) ; closest = Math . min ( closest , distanceSq ( segmentA , segmentB . b ) ) ; closest = Math . min ( closest , distanceSq ( segmentB , segmentA . a ) ) ; closest = Math . min ( closest , distanceSq ( segmentB , segmentA . b ) ) ; return closest ; }
Finds the distance squared between the two line segments