3.2.3 [opt] Rotate the Scene with Keyboard

GLFW key_callback

To support keyboard based rotation, we are adding a global matrix variable matRoot for the root.

We also rot_x and rot_y to keep the accumulated rotation angles.

Define GLFW key_callback() before main() in main.cpp.

The function changes the rotation angle based on arrow keys.

Finally the rotation is saved in matRoot.


glm::mat4 matRoot = glm::mat4(1.0);
float rot_x = 0;
float rot_y = 0;

void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
    if (key == GLFW_KEY_LEFT ) {
        rot_y -= 5.0;
    } else if (key == GLFW_KEY_RIGHT /*&& action == GLFW_PRESS*/) {
        rot_y += 5.0;
    } if (key == GLFW_KEY_DOWN ) {
        rot_x += 5.0;
    } else if (key == GLFW_KEY_UP) {
        rot_x -= 5.0;
    }

    glm::mat4 mat_rot_y = glm::rotate(glm::radians(rot_y), glm::vec3(0.0f, 1.0f, 0.0f));
    glm::mat4 mat_rot_x = glm::rotate(glm::radians(rot_x), glm::vec3(1.0f, 0.0f, 0.0f));

    matRoot =  mat_rot_x * mat_rot_y;
    
}

Set key_callback

In main(), add glfwSetKeyCallback() after glfw window creation to register the key event callback function.

Draw with a root matrix

Finally, in the rendering loop, use matRoot as the argument when call scene->draw()

Now you can play rotating the pyramid with the arrow keys. We can see that the teapot always rotates with cube, which shows that our scenegraph works.

Last updated