# 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.

```cpp

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.

```cpp
    // create a GLFW window
    window = glfwCreateWindow(640, 640, "Hello OpenGL 2", NULL, NULL);
    glfwMakeContextCurrent(window);

    // register the key event callback function
    glfwSetKeyCallback(window, key_callback);
```

## Draw with a root matrix

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

```cpp
    while (!glfwWindowShouldClose(window))
    {
        glfwPollEvents();

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        scene->draw(matRoot);
        
        glfwSwapBuffers(window);
    }
```

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.

<figure><img src="https://3464970502-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3JUKGJZ67JX02QZdPhsy%2Fuploads%2F0DJC3axxMw3WJ5G6KxFO%2Fimage.png?alt=media&#x26;token=0978e086-a5c2-440b-8a64-7c7ed29c73eb" alt=""><figcaption></figcaption></figure>
