Angle between 2 3d Vectors

Started by
6 comments, last by Pinzip 19 years, 12 months ago
Hu all I was wondering if anyone can give me a formula that gives the xz plane(yaw) and y plane(pitch) between 2 points in a 3D enviroment. Thanks Eoin
Advertisement
P1(x,y,z)P2(x,y,z)yaw1 = atan2(P1.y, P1.x);yaw2 = atan2(P2.y, P2.x);deltayaw = yaw2-yaw1;pitch1 = atan2(P1.z, sqrt(P1.x*P1.x+P1.y*P1.y));pitch2 = atan2(P2.z, sqrt(P2.x*P2.x+P2.y*P2.y));deltapitch = pitch2-pitch1;  


PS: this is assuming your Z axis is the up axis (your pitch), you can easily modify this if your Y axis is the up axis...

[edited by - SpaceDude on April 21, 2004 6:15:36 PM]
Perfect, thanks
this is wrong I think. P1 and P2 are positions in space, so you just do

D = P2 - P1
yaw = atan2(D.y, D.x);
pitch = atan2(D.z, sqrt(D.x*D.x+D.y*D.y));

in general you have to be careful when comparing angles, since if say, pitch2 = 355 degrees, and pitch1 = 0 degrees, it will give a deviation of 355 degrees. so you may have to take the minimum between (pitch2 - pitch1), (pitch2 - pitch1) - 360. idem if pitch2 = 0, pitch1 = -355, ...

so always think of wrapping around angle differences, if required.

Everything is better with Metal.

Thats great guys, Thanks
hum... ok maybe i miss-understood your question...

what i was giving you is the difference in yaw and pitch for two vectors:

(0,0,0) to P1(x,y,z)
and
(0,0,0) to P2(x,y,z)

If you wanted just the yaw relative to the positive x-axis and pitch relative to the x/y plane (or x/z) of the vector from P1 to P2 then use what oliii said.
If your vectors are normalised, I think it would be faster to use:

Angle = acos(Vec3Dot(v1, v2))

Particularly if you were using a lookup table for the arccos. But I think having to normalise the vectors manually would probably make this method slower than the one above... Not too sure where to draw the line.
Ring3 Circus - Diary of a programmer, journal of a hacker.
quote:Original post by TheAdmiral
If your vectors are normalised, I think it would be faster to use:

Angle = acos(Vec3Dot(v1, v2))

Particularly if you were using a lookup table for the arccos. But I think having to normalise the vectors manually would probably make this method slower than the one above... Not too sure where to draw the line.


that only gives the angle between the two vectors... not the yaw and pitch between the two vectors...

and nevermind trying to speed up all those trig functions using lookup tables, i saw some other post where people where trying to do it and they failed miserably.

[edited by - SpaceDude on April 24, 2004 11:19:35 AM]

This topic is closed to new replies.

Advertisement