Reputation: 2230
Since OpenGL camera basically looking at negative z direction,
int front = 0, right = 0;
// Press W and move backward?!
front += glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS ? -1 : 0;
front += glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS ? 1 : 0;
// Press D to move right makes sense!
right += glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS ? 1 : 0;
right += glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS ? -1 : 0;
Translate(right, 0, front);
As you can see in the code, in order to move camera forward, I have to move it's z position backward, which completely disobeys my intuition.
So in order to deal with this problem, I deliberately multiplied scale(1, 1, -1)
to my view matrix, like
viewMatrix = glm::inverse(GetWorldTransform());
viewMatrix = glm::scale(glm::mat4(1), glm::vec3(1, 1, -1)) * viewMatrix;
pvMatrix = perspectiveMatrix * viewMatrix;
...Which is not very pretty. Is it okay to solve this problem like this? Or, Is there any way to set OpenGL's camera to look at positive z direction? Or, Is there a prettier way to deal with the problem?
Upvotes: 1
Views: 543
Reputation: 45332
OpenGL doesn't have a camera. It just renders whatever happens to fall into the viewing volume in clip space. The "camera" is just either a completely abstract mental model, or some higher-level abstraction around some transformation math you add on top. As such, you completely define what a "camera" is and where it looks at.
Since OpenGL camera basically looking at negative z direction.
In OpenGL 1.x, there actually was a convention which had something to do with this. The functions glFrustum
and glOrtho
were build for an eye space where -z
was the viewing direction . However, you can use whatever matrices you want, and you could do so since GL 1.0. (The rest of the functions which also adhere to this convention, like gluLookAt
, gluPerspective
, etc. were never part of OpenGL).
Is it okay to solve this problem like this?
Well, it is mathematically correct. In your case, you basically end up with P * S * V
.
Or, Is there any way to set OpenGL's camera to look at positive z direction? Or, Is there a prettier way to deal with the problem?
There is. Instead of doing P * S * V
you could do P' * V
where P' = (P * S)
. And you can calculate P'
without doing the multiplication with a scale matrix (which in this particular case only flips the signs of the 3rd column anyway).
Since you use the glm library, you can let glm do it for you directly - the glm library for some reason uses the old GL conventions by default, but it doesn't enforce them. It leaves you the option to use for example glm::perspectiveLH
or glm::perspectiveLH
. Old GL convention is to use a right-handed view space, but you can directly create the "left-handed" version of the projection matrix.
Upvotes: 2