Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!
Guest

nearest point on line

By: a guest on May 5th, 2011  |  syntax: Java  |  size: 0.68 KB  |  views: 454  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  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.         }