Search code examples
openglrotationglfwglm-math

Glm rotate object by time


I have an object which I want to rotate on key hold using this function

if (key == GLFW_KEY_S && action == GLFW_REPEAT) {
            timer = glfwGetTime();
}

Which sends timer to this rotation

auto rotateMat = rotate(mat4{}, timer * 0.4f, {0, 1, 0});

But problem is, I hold key S pressed and the object is rotating but when I release it, time is changing of course, since glfwGetTime() gets real time. Then I press S again and hold it to rotate, but it starts rotation from different object angle as when it stopped. Any ideas how to fix it?

EDIT:

I have fixed it by using timer += 0.1;

But when I press S and hold it, it has a delay about 1 second until the object starts rotating. It was same with using real glfwGetTime(). How can I have no delay?


Solution

  • You should track if the key is pressed:

    if (action == GLFM_PRESS) {
        keysPressed[key] = true;
    }
    if (action == GLFM_RELEASE) {
        keysPressed[key] = false;
    }
    

    In the render loop:

    now = glfwGetTime();
    double delta = now - lastTime;
    lastTime = now;
    
    if (keysPressed[GLFW_KEY_S]) {
        timer += delta;
    }
    if (keysPressed[GLFW_KEY_A]) {
        timer -= delta;
    }
    auto rotateMat = rotate(mat4{}, timer * 0.4f, {0, 1, 0});