I posted about this before and thought I'd solved it - I'm close, but it seems I still don't have it working correctly.
I'm trying to make a spaceship turn towards the player. To do this, I find the desired direction vector from the two positions.
I first tried flattening this vector onto the z/y and z/x planes, and using the dot product to find the angles seperately. This works, but as the ship lines up the angle between direction and intended direction gets very small, and the dot product starts producing NaN...
I've read that I can use atan2 to find the required yaw/pitch angles as well as the turn direction, but I can't get it to work.
float pitchAngle = atan2f(myDirection.y - goalDirection.y, myDirection.z - goalDirection.z);
With the ship at (0, 80, -400) moving in (0, 0, 1) towards the player at the origin, the pitch angle should be 78.7 degrees. However, it comes out as 84 degrees.
If I use positions instead of directions instead, i.e.
float pitchAngle = atan2f(myPosition.y - goalPosition.y, myPosition.z - goalPosition.z);
I get the right angle in some cases, depending on which way the ship is moving with respect to the player.
Does anyone know the correct calculations for yaw and pitch?
Thanks