1

I have a point (x1, y1, z1) in a 3D dimensional space And a line (x2,y2,z2)(x3,y3,z3)

I want to find the shortest distance between the line and the dot. I already found mathematical equations for this, but I am not a mathematician, and i failed to understand the different variables in the equation and apply them to Java/Android.

I have searched and viewed the similar questions here and almost everywhere, but there were no example in any programming language.

Rami Dabain
  • 4,709
  • 12
  • 62
  • 106
  • http://stackoverflow.com/questions/9368436/3d-perpendicular-point-on-line-from-3d-point, requires hardly any effort to convert to Java; but is strictly for infinite lines –  Jul 13 '16 at 13:20

2 Answers2

1

After spending the night learning some spacial math, I could finally convert the equations to Java code:

public static float betweenPointAndLine(float[] point, float[] lineStart, float[] lineEnd){
        float[] PointThing = new float[3];
        float[] TotalThing = new float[3];
        PointThing[0] = lineStart[0] - point[0];
        PointThing[1] = lineStart[1] - point[1];
        PointThing[2] = lineStart[2] - point[2];

        TotalThing[0] = (PointThing[1]*lineEnd[2] - PointThing[2]*lineEnd[1]);
        TotalThing[1] = -(PointThing[0]*lineEnd[2] - PointThing[2]*lineEnd[0]);
        TotalThing[2] = (PointThing[0]*lineEnd[1] - PointThing[1]*lineEnd[0]);

    float distance = (float) (Math.sqrt(TotalThing[0]*TotalThing[0] + TotalThing[1]*TotalThing[1] + TotalThing[2]*TotalThing[2]) /
                    Math.sqrt(lineEnd[0] * lineEnd[0] + lineEnd[1] * lineEnd[1] + lineEnd[2] * lineEnd[2] ));


    return distance;
}
Rami Dabain
  • 4,709
  • 12
  • 62
  • 106
0
public static double distance(double x1, double y1, double z1,
                              double x2, double y2, double z2,
                              double x3, double y3, double z3) {
    double b = Math.sqrt(Math.pow((x2 - x3), 2) 
            + Math.pow((y2 - y3), 2) 
            + Math.pow((z2 - z3), 2));

    double S = Math.sqrt(Math.pow((y2 - y1) * (z3 - z1) - (z2 - z1) * (y3 - y1), 2) +
            Math.pow((z2 - z1) * (x3 - x1) - (x2 - x1) * (z3 - z1), 2) +
            Math.pow((x2 - x1) * (y3 - y1) - (y2 - y1) * (x3 - x1), 2)) / 2;

    return 2 * S / b;
}
Sharpe
  • 406
  • 4
  • 8