How do you calculate pitch & yaw for a camera so that it faces a certain 3D point?
Variables
- Camera X, Y, Z
- Point X, Y, Z
Current Half Solution
Currently I know how to calculate the pitch, and I do that using the following.
$dx:=camera_x-point_x$
$dy:=camera_y-point_y$
$dz:=camera_z-point_z$
$pitch:=atan2(\sqrt{dz*dz+dx*dx},dy))$
Then if $(dy>0)$ pitch gets negated. ($pitch:=-pitch$)
The Main Question
So how would I go about calculating the yaw?
Edit
This is the orientation of my axis.
(source: wikispaces.com)
Answer – Thanks to Omnomnomnom
$dx:=camera_x-point_x$
$dy:=camera_y-point_y$
$dz:=camera_z-point_z$
$pitch:=-atan2(dy, \sqrt{dx*dx+dz*dz})$
$yaw:=atan2(dz,dx)-90^\circ$
Best Answer
So, we're going to describe camera direction needed to direct the camera positioned at $(0,0,0)$ at an $(x,y,z)$ point using the angles from spherical coordinates. The two angles are $\theta$ and $\phi$.
$\theta$, the azimuthal angle, normally taken from $0˚$ to $360˚$, is the angle made in the $xy$ plane between the $x$-axis and the line connecting $(0,0,0)$ to $(x,y,0)$. Simply put, this gives us our "yaw".
$\phi$, the polar angle, normally taken from $0˚$ to $180˚$, is the angle made between the $z$-axis and the line connecting $(0,0,0)$ to $(x,y,z)$. This gives us something like the pitch. That is, $\phi=90˚$ means that you're looking horizontally, whereas $\phi=0˚$ means that you're looking vertically upward.
Now, for a given point $(x,y,z)$, the calculations are as follows: $$ \theta = \arctan\left(\frac yx\right)\\ \phi = \arctan\left(\frac {\sqrt{x^2+y^2}}z\right) $$ So for example: to point your camera at the point $(1,1,1)$, you would need the angles $$ \theta = \arctan\left(\frac 11\right)=45˚\\ \phi = \arctan\left(\frac {\sqrt{2}}1\right) \approx 55˚ $$