Advertisement
HenriAugusto

distanceBetweenPointAndLine and distanceBetweenPointAndSegm

Feb 24th, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.52 KB | None | 0 0
  1. static double distanceBetweenPointAndLine(Vector2D point, Vector2D linePoint0, Vector2D linePoint1) {
  2.         //the variable names on the function arguments makes it clear how to use the function
  3.         //but now i will use shorter names
  4.         Vector2D pt = point;
  5.         Vector2D lp0 = linePoint0;
  6.         Vector2D lp1 = linePoint1;
  7.         double numerator = (lp0.y - lp1.y) * pt.x + (lp1.x - lp0.x) * pt.y + (lp0.x * lp1.y - lp1.x * lp0.y);
  8.         double denumerator = sqrt(
  9.                 pow(lp1.x - lp0.x, 2) + pow(lp1.y - lp0.y, 2)
  10.         );
  11.         return abs(numerator / denumerator);
  12.     }
  13.    
  14.     static float distanceBetweenPointAndSegment(Vector2D point, Vector2D segPoint1, Vector2D segPoint2){
  15.         //Vector representing our segment
  16.         Vector2D segment = Vector2D.sub(segPoint2, segPoint1);
  17.         //our point relative to segPoint1
  18.         Vector2D relativePoint = Vector2D.sub(point, segPoint1);
  19.         //Angle of the segment
  20.         float segmentAngle = segment.heading();
  21.         //makes it parallel to the X axis
  22.         segment.rotate( TWO_PI-segmentAngle );
  23.         //rotates the point accordingly
  24.         relativePoint.rotate( TWO_PI-segmentAngle );
  25.         if( relativePoint.x < 0){
  26.             return distanceBetweenPoints(relativePoint,segPoint1);
  27.         } else if( relativePoint.x > segment.x){
  28.             return distanceBetweenPoints(relativePoint,segPoint2);
  29.         } else {
  30.             return (float) distanceBetweenPointAndLine(point, segPoint1, segPoint2);
  31.         }
  32.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement