Search code examples
c++opengl3dtransformationglm-math

Z coordinates are flipped when using glm


I am trying to render a 3D model using OpenGL. And for the projection and transformation matrices, I am using glm. I've got my model on the screen and it works just like I intended it to; except one small problem.

I am setting the model's translation matrix as

glm::translate(glm::vec3(0, 0, 4)

to move the model a little bit forward so that I can see it. Since in OpenGL, by default, negative z is out towards the 'camera' and positive z is forward, I expected this to work but it doesn't. It only works if I set it to

glm::translate(glm::vec3(0, 0, -4)

But this seems weird to me, as I am setting my zNear to 0.01 and zFar to 1000. Is glm's z values flipped or am I doing something wrong here?

Here is my code:

glm::mat4 rotation = glm::mat4(1.0f);
glm::mat4 translation = glm::translate(glm::vec3(0, 0, -4));
glm::mat4 scale = glm::mat4(1.0f);

glm::mat4 modelMatrix = translation * rotation * scale;

glm::mat4 projectionMatrix = glm::perspective(70.0f, aspectRatio, 0.01f, 1000.0f);

glm::mat4 transformationMatrix = projectionMatrix * modelMatrix;

Solution

  • When you call perspective() with near = 0.01 and far = 1000.0 planes, its actual meaning is that you are cutting it as -0.01 to -1000.0 so you should put the object's z-value into the range [-0.01, -1000.0].

    Imagine the right handed Coordinate and assume your eye's z-value is 0.0 in default. enter image description here