Here you can find the source of distanceFromLineToPoint(double x1, double y1, double z1, double x2, double y2, double z2, double px, double py, double pz)
Parameter | Description |
---|---|
x1 | a parameter |
y1 | a parameter |
z1 | a parameter |
x2 | a parameter |
y2 | a parameter |
z3 | a parameter |
px | a parameter |
py | a parameter |
pz | a parameter |
public static double distanceFromLineToPoint(double x1, double y1, double z1, double x2, double y2, double z2, double px, double py, double pz)
//package com.java2s; public class Main { /**//from ww w . ja v a2 s . c o m * Get the shortest distance from a line segment to a point * @param x1 * @param y1 * @param z1 * @param x2 * @param y2 * @param z3 * @param px * @param py * @param pz * @return the distance, which will be >= 0.0; or -1.0, if the point is beyond the segment's ends */ public static double distanceFromLineToPoint(double x1, double y1, double z1, double x2, double y2, double z2, double px, double py, double pz) { double ddx = x2 - x1; double ddy = y2 - y1; double ddz = z2 - z1; double lineMag = ddx * ddx + ddy * ddy + ddz * ddz; double u = (((px - x1) * ddx) + ((py - y1) * ddy) + ((pz - z1) * ddz)) / lineMag; if (u < 0.0f || u > 1.0f) { return -1.0; // closest point does not fall within the line segment } double ix = x1 + u * (x2 - x1); double iy = y1 + u * (y2 - y1); double iz = z1 + u * (z2 - z1); ddx = ix - px; ddy = iy - py; ddz = iz - pz; return Math.sqrt(ddx * ddx + ddy * ddy + ddz * ddz); } public static double distanceFromLineToPoint(double x1, double y1, double x2, double y2, double px, double py) { return distanceFromLineToPoint(x1, y1, 0.0, x2, y2, 0.0, px, py, 0.0); } }