سؤال

I loaded an object from a .obj file. I am trying to apply a glm::rotate, glm::translate, glm::scale to it.

The movement (translation and rotation) is made using keyboard input like this;

// speed is 10
// angle starts at 0
if (keys[UP]) {
    movex += speed * sin(angle);
    movez += speed * cos(angle);
}
if (keys[DOWN]) {
    movex -= speed * sin(angle);
    movez -= speed * cos(angle);
}
if (keys[RIGHT]) {
    angle -= PI / 180;
}
if (keys[LEFT]) {
    angle += PI / 180;
}

and then, the transformations:

// use shader
glUseProgram(gl_program_shader);

// send the uniform matrices to the shader
glUniformMatrix4fv(glGetUniformLocation(gl_program_shader, "model_matrix"), 1, false, glm::value_ptr(model_matrix));
glUniformMatrix4fv(glGetUniformLocation(gl_program_shader, "view_matrix"), 1, false, glm::value_ptr(view_matrix));
glUniformMatrix4fv(glGetUniformLocation(gl_program_shader, "projection_matrix"), 1, false, glm::value_ptr(projection_matrix));

glm::mat4 rotate    = glm::rotate(model_matrix, angle, glm::vec3(0, 1, 0));
glm::mat4 translate = glm::translate(model_matrix, glm::vec3(RADIUS + movex, 0, -RADIUS + movez));
glm::mat4 scale     = glm::scale(model_matrix, glm::vec3(20.0, 20.0, 20.0));

glUniformMatrix4fv(glGetUniformLocation(gl_program_shader, "model_matrix"), 1, false, glm::value_ptr(translate * scale * rotate));
glBindVertexArray(ironMan->vao);
glDrawElements(GL_TRIANGLES, ironMan->num_indices, GL_UNSIGNED_INT, 0);

If I don't use KEY_RIGHT / KEY_LEFT, it works as expected (which means that it translates the object forward and backward). If I use them, it rotates around it's own center, but when I press KEY_UP / KEY_DOWN, it translates ... well, not as expected.

I've put on the notifyKeyPressed() function a case to print out the movex, movey and angle value and it seems that the angle is not the one that it should:

  • when the IronMan is with it's back at me, angle = 0 - this is the start point;
  • when the IronMan is with his face on the right, the angle should be around -PI / 2 (-1.57), but it is around -80/-90.

I thought this was because of the glm::scale, but I changed the values and nothing changed.

Any idea why is the angle acting like this?

هل كانت مفيدة؟

المحلول

Your rotation center stays at the origin, you need to translate the rotation center of your object to the origin, make your scale, rotation, translate back, then translate.

EDIT More importantly related to your exact problem, glm::rotate works in degrees.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top