GLFW4——画一个左右移动的三角形

实现思路:通过uniform对象,每次画面刷新的时候,把偏移值由CPU传入GPU

关键代码:
Shader.vs

#version 330 core
layout (location = 0) in vec3 position; 

uniform vec3 offset;

void main()
{
    gl_Position = vec4(position+offset, 1.0);
}
    // Game loop
    while (!glfwWindowShouldClose(window))
    {
        // Check if any events have been activiated (key pressed, mouse moved etc.) and call corresponding response functions
        glfwPollEvents();
        
        // Render
        // Clear the colorbuffer
        glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);
        
        // Draw our first triangle
        shader.Use();
        
        glBindVertexArray(VAO);
        glDrawArrays(GL_TRIANGLES, 0, 3);
        
        GLfloat timeValue = glfwGetTime();
        
        GLfloat x = (sin(timeValue) / 2);
        GLint vertexOffsetLocation = glGetUniformLocation(shader.Program, "offset");
        glUniform3f(vertexOffsetLocation, x, 0, 0.0f);
        
        glBindVertexArray(0);
        
        // Swap the screen buffers
        glfwSwapBuffers(window);
    }

glGetUniformLocation返回shader里面uniform句柄,接下来就使用glUniformXXX給它传值。

你可能感兴趣的:(GLFW4——画一个左右移动的三角形)