Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static Point2D nearestPointOnLine(double ax, double ay, double bx, double by, double px, double py,
- boolean clampToSegment, Point2D dest) {
- // Thanks StackOverflow!
- // http://stackoverflow.com/questions/1459368/snap-point-to-a-line-java
- if (dest == null) {
- dest = new Point2D.Double();
- }
- double apx = px - ax;
- double apy = py - ay;
- double abx = bx - ax;
- double aby = by - ay;
- double ab2 = abx * abx + aby * aby;
- double ap_ab = apx * abx + apy * aby;
- double t = ap_ab / ab2;
- if (clampToSegment) {
- if (t < 0) {
- t = 0;
- } else if (t > 1) {
- t = 1;
- }
- }
- dest.setLocation(ax + abx * t, ay + aby * t);
- return dest;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement