daily pastebin goal
59%
SHARE
TWEET

nearest point on line

a guest May 5th, 2011 945 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.         public static Point2D nearestPointOnLine(double ax, double ay, double bx, double by, double px, double py,
  2.                         boolean clampToSegment, Point2D dest) {
  3.                 // Thanks StackOverflow!
  4.                 // http://stackoverflow.com/questions/1459368/snap-point-to-a-line-java
  5.                 if (dest == null) {
  6.                         dest = new Point2D.Double();
  7.                 }
  8.  
  9.                 double apx = px - ax;
  10.                 double apy = py - ay;
  11.                 double abx = bx - ax;
  12.                 double aby = by - ay;
  13.  
  14.                 double ab2 = abx * abx + aby * aby;
  15.                 double ap_ab = apx * abx + apy * aby;
  16.                 double t = ap_ab / ab2;
  17.                 if (clampToSegment) {
  18.                         if (t < 0) {
  19.                                 t = 0;
  20.                         } else if (t > 1) {
  21.                                 t = 1;
  22.                         }
  23.                 }
  24.                 dest.setLocation(ax + abx * t, ay + aby * t);
  25.                 return dest;
  26.         }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top