无法在 OpenGL 中随时间更改颜色

Failed to change color over time in OpenGL

本文关键字:时间 颜色 OpenGL      更新时间:2023-10-16

我正在使用OpenGL超级圣经第7版学习OpenGL。但是,当我尝试运行第 2 章中的示例时,我发现了一个问题,即颜色没有按预期随时间变化。

这是主要程序:

int main(int argc, char** argv) {
    if (!glfwInit())
    {
        fprintf(stderr, "Failed to initialize GLFWn");
        return 1;
    }
    GLFWwindow* window;
    window = glfwCreateWindow(800, 600, "My First OpenGL Project", NULL, NULL);
    if (!window)
    {
        fprintf(stderr, "Failed to open windown");
        return 1;
    }
    glfwMakeContextCurrent(window);
    gl3wInit();
    bool running = true;
    do
    {
        double current_time = glfwGetTime();
        static const GLfloat color[] = {
            (float)sin(current_time) * 0.5f + 0.5f,
            (float)cos(current_time) * 0.5f + 0.5f,
            0.0f,
            1.0f };
        std::cout << current_time << std::endl;
        std::cout << color[0] << std::endl;
        glClearBufferfv(GL_COLOR, 0, color);
        glfwSwapBuffers(window);
        glfwPollEvents();
        running &= (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_RELEASE);
        running &= (glfwWindowShouldClose(window) != GL_TRUE);
    } while (running);
    glfwDestroyWindow(window);
    glfwTerminate();
    return 0;
}

看起来current_time的值会随着时间的推移而变化,但颜色[0]的值却没有。为什么?

发生这种情况是因为静态变量的初始值设定项仅在初始化变量时调用一次。此外,const 是一个很好的提示,表明这个变量永远不会改变。

因此,如果您希望每个帧都有不同的颜色,请删除static const并坚持使用

GLfloat color[] = {
        (float)sin(current_time) * 0.5f + 0.5f,
        (float)cos(current_time) * 0.5f + 0.5f,
        0.0f,
        1.0f };