Getting angle of a line?

I am trying to find the angle of a line in 3D space. As far as I can tell there should be two angles, one horizontal and the other vertical. In 2D coordindate system I have the following algorithm:


    double x = line.getX2() - line.getX1();
    double y = line.getY2() - line.getY1();   

    double v = y/x;
    double angle = Math.atan(v);
    if ( v < 0)
      angle = Math.PI + angle;
    if ( y < 0 ) 
      angle = angle + Math.PI;
    return angle;

But I am not sure what I would do in 3D space. Any help would be appreciated.

im very bad at 3D and havin probs with quaternions but maybe i can help. For a 2d, you have x and y axis to check, keep that code and try doing another function that does the x and z after.

In the 2D case, the angle of a line is basically the theta component of a point’s polar coordinates.
The 3D equivalent of a polar coordinate is (drumroll) Spherical coordinates

Hope that helps

I am wondering whether it is that simple:

Imagine a line p1(1,1,1)-p2(3,4,5), which gives (p2-p1) being (2,3,4). Now there are three view points( y/x, z/x and y/z), so

arctan(y/x) is 56.3º,
arctan(z/x) is 63.4º
arctan(y/z) is 36.9º

Since should only be a vertical and horizontal plain, I seem to have too many angles. Maybe I should be averaging arctan(y/x) with arctan(z/x) and then arctan(z/x) with arctan(y/z)? I am hoping someone with a bit more experience could help me out.

BTW The Wolfram pages are confusing me. I know really need to improve my maths, but that is work in progress :slight_smile:

with x,y,z == vector from point a to point b

x=p1.x-p2.x;
y=p1.y-p2.y;
z=p1.z-p2.z;

this code sample will return angle rx,ry relative to z axis (left hand) and performed in order RX than RY


double n=Math.sqrt(x*x+y*y+z*z);
if(n==0.0) return this;
x/=n;
y/=n;
z/=n;

double nzx=Math.sqrt(x*x+z*z);
double rx=Math.asin(y);
double ry=0;
if(nzx!=0.0)
ry=-Math.acos(z/nzx);
else
{
ry=0;
}

if(x<0)
ry=-ry;


System.out.println("rx="+rx);
System.out.println("ry="+ry);

Bruno

Thanks Bruno. Exactly what I was looking for :slight_smile: