# Camera Math for Directions

I have a Camera object that has the variables:

class Camera : Object
{
public:
float positionX, positionY, positionZ;
float directionX, directionY, directionZ;
int speed;
}


The positions are what I will draw my scene's position based on, the direction is a value between 0 and 1 that I will multiply for the speed to get the next position:

if(keyboardInput.GetKeyState(Key::ArrowUp) == KeyState::Pressed)
{
_viewCamera.positionX = _viewCamera.directionX * _viewCamera.speed;
_viewCamera.positionY = _viewCamera.directionY * _viewCamera.speed;
_viewCamera.positionZ = _viewCamera.directionZ * _viewCamera.speed;
}


The problem is the rotation direction, which I'm calculating with:

if(mouseInput.GetButtonState(Button::RightButton) == ButtonState::Pressed)
{
//Here I get how many pixels the mouse moved between the X and Y axis with mouse sensitivity accounted for
float rotationX = mouseInput.GetMouseMoveX();
float rotationY = mouseInput.GetMouseMoveY();

_viewCamera.directionX = sin(rotationX * 3.1415/180);
_viewCamera.directionY = sin(rotationY * 3.1415/180);

_viewCamera.directionZ = cos(rotationX * 3.1415/180);
}


There is something missing here, but I can't get it right. The direction when I'm looking to the left or right works fine, but when I look up or down I'm not taking into account the rotationY for calculating the Z direction.

This means, if I'm looking straightly down, I'm not supposed to move forward or backwards, just down along the Y axis. But I'm going forward/backward because I'm not calculating the rotationY in the directionZ.

I tried subtracting the cos(rotationY) to directionZ, but the movement didn't felt right (was pretty weird actually).

What's the proper math so I get the correct movement along all axis?

float rotationX = mouseInput.GetMouseMoveX();
float rotationY = mouseInput.GetMouseMoveY();

const float radius = 3.0f;
_viewCamera.directionY = radius * sinf(rotationY);
float r = radius * cosf(rotationY);
_viewCamera.directionZ = r * cosf(rotationX);
_viewCamera.directionX = r * sinf(rotationX);


To make it look properly you need to consider point you look at as some point on the sphere with longitude/latitude. You may need to adjust sensitivity/make it opposite directions if needed by changing 3.0 to -3.0.

But you will most likely run into problems when your longitude reaches PI. This example from Microsoft will help you to implement camera properly. (BasicCamera/LonLatController)

• I don't use the radius value, the speed and limitations on the angles I'm looking I'm limiting it already in the code. So I just added the cos(rotationY) and multiplied it for the Z direction and it worked perfectly! Thanks! Mar 5, 2013 at 7:31