我無法弄清楚爲什麼下面的代碼不起作用,我試圖繪製2個形狀,一個紅色的三角形和一個多色的立方體如果我試圖同時繪製它,它會給出奇怪的錯誤,我試圖圍繞改變變量修改着色器來改變線條,而且我看起來不能接近我想要的結果,當前代碼最終繪製了使用立方體的2個相同的三角形顏色。不能在opengl中繪製多個對象
GLuint VertexArrayID;
glGenVertexArrays(1, &VertexArrayID);
glBindVertexArray(VertexArrayID);
GLuint MatrixID = glGetUniformLocation(shader->id(), "MVP");
glm::mat4 Projection = glm::perspective(45.0f, 4.0f/3.0f, 0.1f, 100.0f);
glm::mat4 View = glm::lookAt(
glm::vec3(4,2,2), // Camera location
glm::vec3(0,0,0), // and looks at the origin
glm::vec3(0,1,0) // Head is up (set to 0,-1,0 to look upside-down)
);
glm::mat4 myMatrix = glm::translate(-2.f,0.f,0.f);
glm::mat4 Model = glm::mat4(1.f);
Model= myMatrix * Model;
glm::mat4 MVP = Projection * View * Model;
glm::mat4 myMatrix2 = glm::translate(2.f,0.f,0.f);
glm::mat4 Model2 = glm::mat4(1.f);
Model2= myMatrix2 * Model2;
glm::mat4 MVP2 = Projection * View * Model2;
glViewport(0, 0, windowWidth, windowHeight); // set viewport to the size of the window
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
shader->bind();
glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP[0][0]);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,0,(void*)0);
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, colourBuffer);
glVertexAttribPointer(1,3,GL_FLOAT,GL_FALSE,0,(void*)0);
glDrawArrays(GL_TRIANGLES,0,12*3);
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP2[0][0]);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer2);
glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,0,(void*)0);
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, colourBuffer2);
glVertexAttribPointer(1,3,GL_FLOAT,GL_FALSE,0,(void*)0);
glDrawArrays(GL_TRIANGLES, 0, 3);
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
SwapBuffers(hdc);
glDeleteBuffers(1, &vertexBuffer);
glDeleteBuffers(1, &vertexBuffer2);
glDeleteBuffers(1, &colourBuffer);
glDeleteBuffers(1, &colourBuffer2);
shader->unbind();
glDeleteVertexArrays(1, &VertexArrayID);
這就是主要代碼。我通過基本上使用下面3行中的變化,以插入不同的緩衝名稱和數據創建以類似的方式,所有的緩衝器,
glGenBuffers(1, &vertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glBufferData(GL_ARRAY_BUFFER,sizeof(Cube), Cube, GL_STATIC_DRAW);
片段着色器
#version 330 core
in vec3 fragmentColour;
out vec3 colour;
void main(){
colour = fragmentColour;
}
頂點着色器
#version 330 core
uniform mat4 MVP;
layout(location = 0) in vec3 vertexPosition_modelspace;
layout(location = 1) in vec3 vertexColour;
out vec3 fragmentColour;
void main(){
gl_Position = MVP * vec4(vertexPosition_modelspace,1);
fragmentColour = vertexColour;
}
由於您使用的是VAO,因此您可以創建其中的兩個,併爲其中的每個形狀保存VBO綁定,以便您不必每次都設置所有屬性。 – Detheroc