Opengl 程序无法识别第二个顶点输入

Opengl program not recognizing second vertex input

我正在阅读有关着色器和颜色的内容,如何将它们定义为顶点输入。所以我按照教程来了,结果一团糟,因为程序只是向前阅读而不是进入下一行:

GLfloat vertecies[] = {
    //vertices              colors
    0.5f, -0.5f, 0.0f,      1.0f, 0.0f, 0.0f,// Bottom Right
    -0.5f, -0.5f, 0.0f,     0.0f, 1.0f, 0.0f,// Bottom Left
    0.0f,  0.5f, 0.0f,      0.0f, 0.0f, 1.0f,// Top 
};

下面是将第二个顶点输入设置为颜色的代码:

glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertecies), vertecies, GL_STATIC_DRAW);

glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(index), index, GL_STATIC_DRAW);

glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0);
glEnableVertexAttribArray(0);

glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
glEnableVertexAttribArray(1);

glBindVertexArray(0);

这是我的顶点着色器代码:

const char* VertexShaderCode =
 "#version 330 core\r\n"
 ""
 "layout(location=0) in vec3 position;"
 "layout(location=1) in vec3 color;"
 ""
 "out vec3 theColor;"
 ""
 "void main()"
 "{"
 "  gl_Position = vec4(position, 1.0);"
 "  theColor = color;"
 "}";

这是片段着色器代码:

const char* FragmentShaderCode =
 "#version 330 core\r\n"
 ""
 "in vec3 theColor;"
 ""
 "out vec4 color;"
 ""
 "void main()"
 "{"
 "  color = theColor;"
 "}";

告诉我,如果我做错了什么。

您的属性索引 0 的步幅乘数是错误的。它应该是 6,因为一个顶点包含 3 个位置元素和 3 个颜色元素。替换

glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0);

glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)0);