Andrew
Andrew

Reputation: 1784

Moving object stutters using delta time to unify speed

I have tried different machines, VSync on and off.

I have provided my main method and display method. In the main look I calculate delta using GLFWs GetTime method.

If I explicitly set deltaTime = 0.016 to lock the target speed, the triangle moves smoothly.

int main(int argc, char** argv)
{
    /*
        INIT AND OTHER STUFF SNIPPED OUT
    */

    double currentFrame = glfwGetTime();
    double lastFrame = currentFrame;
    double deltaTime;

    double a=0;
    double speed = 0.6;
    //Main loop
    while(true)
    {
        a++;

        currentFrame = glfwGetTime();
        deltaTime = currentFrame - lastFrame;
        lastFrame = currentFrame;

        /** I know that delta time is around 0.016 at my framerate **/
        //deltaTime = 0.016;

        x = sin( a * deltaTime * speed ) * 0.8f;
        y = cos( a * deltaTime * speed ) * 0.8f;

        display();

        if(glfwGetKey(GLFW_KEY_ESC) || !glfwGetWindowParam(GLFW_OPENED))
            break;
    }

    glfwTerminate();

    return 0;
}

void display()
{
    glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);

    glUseProgram(playerProgram);

        glUniform3f(playerLocationUniform,x,y,z);

        glBindBuffer(GL_ARRAY_BUFFER, playerVertexBufferObject);

        glEnableVertexAttribArray(0);
            glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, 0);
            glDrawArrays(GL_TRIANGLES, 0, 3);
        glDisableVertexAttribArray(0);

    glUseProgram(0);
    glfwSwapBuffers();

}

Upvotes: 2

Views: 9994

Answers (1)

paddy
paddy

Reputation: 63481

You are using deltaTime as if it was a global framerate and calculating the sine and cosine based on a frame number (a) multiplied by that rate. What that means is a minor fluctuation in deltaTime between frames will cause larger changes in position as a becomes larger.

In the other case, where you set a constant deltaTime, you still get small glitches when a frame is rendered at the wrong time.

What you actually need to do is this:

#define TAU (M_PI * 2.0)

    currentFrame = glfwGetTime();
    deltaTime = currentFrame - lastFrame;
    lastFrame = currentFrame;

    a += deltaTime * speed;

    // Optional, keep the cycle bounded to reduce precision errors
    // if you plan to leave this running for a long time...
    if( a > TAU ) a -= TAU;

    x = sin( a ) * 0.8f;
    y = cos( a ) * 0.8f;

Upvotes: 8

Related Questions