Search code examples
c++openglglm-mathrotational-matrices

Am I correctly rotating my model using matrices?


I have been getting unexpected behavior while trying to rotate a basic cube. It may be helpful to know that translating the cube works correctly in the y and z direction. However, translating along the x axis is backwards(I negate only x for proper results) which I haven't been able to figure out why.

Furthermore, rotating the cube has been a mess. Without any sort of transform the cube appears correctly. Once I add a rotation transformation the cube is not displayed until I change one of the x,y,z rotation values from 0(Putting all values back to 0 makes it disappear again). Once it appears the cube won't rotate around whichever x,y,z plane I first changed unless I change two or more of the coordinates. It also wobbles around its origin when rotating.

Below is a snippets of my code I believe has incorrect math.

/* Here's how I setup the matrices for a mvp matrix*/

proj = glm::perspective(glm::radians(90.0f), (960.0f / 540.0f), 0.1f, 400.0f);
view = glm::lookAt(glm::vec3(0, 0, -200), glm::vec3(0, 0, 0), glm::vec3(0, 1, 0));
glm::mat4 model = glm::mat4(1.0f);


/* Here's how I transform the model matrix, note 
   translating works properly once the cube is visible*/

model = glm::translate(model, glm::vec3(-translation[0], translation[1], translation[2])); //negative x value
model = glm::rotate(model, 30.0f, rotation);
glm::mat4 mvp = proj * view * model;
shader->Bind();
shader->SetUniformMat4f("MVP", mvp);
renderer.Draw(*c_VAO, *c_EBO, *shader);


/* Here's how I use these values in my vertex shader */

layout(location = 0) in vec4 position;
... 
uniform mat4 MVP;
...
void main()
{
    gl_Position = u_MVP * position;
    ....
};

I've checked both the translation and rotation vectors values and they are as expected but I am still going mad trying to figure out this problem.


Solution

  • The unit of the angle of glm::rotate is radians. Use glm::radians to convert form degrees to radians:

    model = glm::rotate(model, 30.0f, rotation);

    model = glm::rotate(model, glm::radians(30.0f), rotation);