I am trying to implement the movement of the camera with the mouse. The result I want to achieve is the same that you get when you move your aim in a first person shooter.
Here is the code I wrote, where "camera" is the vector which contains the location of the camera, "center" is the vector which contains the location of the point to which the camera is pointing at, and "move_vector" is simply "center" minus "camera"
if(mouse_move_x != 0 || mouse_move_y != 0){
float a0 = Array_norm<float>(move_vector,3);
Array_copy<float>(move_vector,move_vector2,3);
//perform mouse horizontal axis movement
current_x_angle = atan2(move_vector[2],move_vector[0]);
current_x_angle = current_x_angle + mouse_move_x * input::MOUSE_sensitivity * 0.017;
move_vector[0] = cos(current_x_angle)*a0;
move_vector[2] = sin(current_x_angle)*a0;
//perform mouse vertical axis movement
temp = sqrt(move_vector2[0]*move_vector2[0]+move_vector2[2]*move_vector2[2]);
current_y_angle = atan2(move_vector2[1],temp);
current_y_angle = current_y_angle - mouse_move_y * input::MOUSE_sensitivity * 0.017;
move_vector2[1] = sin(current_y_angle)*a0;
if(move_vector2[0]==0){
move_vector2[2] = (move_vector2[2] >= 0) ? cos(current_y_angle)*a0 : -cos(current_y_angle)*a0;
}
else{
temp2 = move_vector2[2]/move_vector2[0];
temp = cos(current_y_angle)*a0*sqrt(1/(1+temp2*temp2));
move_vector2[0] = (move_vector2[0] >= 0) ? temp : -temp;
move_vector2[2] = move_vector2[0]*temp2;
}
//join x and y movements
Array_sum<float>(move_vector,move_vector2,move_vector,3);
Array_normalize<float>(move_vector,move_vector,3);
center[0] = move_vector[0] + camera[0];
center[1] = move_vector[1] + camera[1];
center[2] = move_vector[2] + camera[2];
}
Two questions:
- the code works only when I consider only one of the due movements (either horizontal movement or vertical movement). The code does not work when I get both movements combined and I cannot understand why
- Is there a better (and more mathematically compact) approach to compute the new camera position and focus point? I am sure there is :)
Thank you