移动物体使用增量时间卡顿以统一速度

Moving object stutters using delta time to unify speed

本文关键字:速度 时间 移动      更新时间:2023-10-16

我尝试过不同的机器,VSync 开机和关机。

我已经提供了我的主要方法和显示方法。在主要外观中,我使用 GLFW 的 GetTime 方法计算增量。

如果我显式设置 deltaTime = 0.016 以锁定目标速度,则三角形移动平稳。

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();
}

您使用deltaTime就好像它是全局帧速率一样,并根据帧数(a)乘以该速率计算正弦和余弦。 这意味着帧之间deltaTime的微小波动将随着a变大而引起更大的位置变化。

在另一种情况下,您设置了一个常量deltaTime ,当帧在错误的时间渲染时,您仍然会遇到小故障。

您实际需要做的是:

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