颜色向量有四个分量RGBA,之前只是用了RGB颜色分量,从来没有使用过A-alpha透明度,今天看了一下资料,简单总结一下。
1、在frag着色器中使用discard,对透明度小于0.1的片段进行丢弃
#version 330 core out vec4 color; uniform sampler2D texture1; in vec3 FragPos; in vec2 TexCoords; void main() { color=texture(texture1, TexCoords); if(color.a<0.1f){ discard; } }
效果图:(图中的草是一张方形的纹理图,可以对alpha<0.1f的部分进行丢弃,只绘制草的部分)
2、开启混合功能,呈现透明感
void Display() { std::vector<glm::vec3> windows { glm::vec3(-1.5f, 0.0f, -0.48f), glm::vec3(1.5f, 0.0f, 0.51f), glm::vec3(0.0f, 0.0f, 0.7f), glm::vec3(-0.3f, 0.0f, -2.3f), glm::vec3(0.5f, 0.0f, -0.6f) }; //setup blend glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // draw objects shader_cube->use(); glm::mat4 projection = phc.getProjectionMatrix(); glm::mat4 view = phc.getViewMatrix(); glm::mat4 model = glm::mat4(1.0f); shader_cube->setMat4("projection", projection); shader_cube->setMat4("view", view); // cubes glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, cubeTexture); model = glm::translate(model, glm::vec3(-1.0f, 0.0f, -1.0f)); shader_cube->setMat4("model", model); cube->DrawCube(); model = glm::mat4(1.0f); model = glm::translate(model, glm::vec3(2.0f, 0.0f, 0.0f)); shader_cube->setMat4("model", model); cube->DrawCube(); // floor glBindTexture(GL_TEXTURE_2D, floorTexture); model = glm::mat4(1.0f); shader_cube->setMat4("model", model); cube->DrawFloor(); // transparent glBindTexture(GL_TEXTURE_2D, transparentTexture); std::map<float, glm::vec3> sorted; for (unsigned int i = 0; i < windows.size(); i++) { float distance = glm::length(phc.getPos() - windows[i]); sorted[distance] = windows[i]; } for (std::map<float,glm::vec3>::reverse_iterator it=sorted.rbegin(); it!=sorted.rend(); it++) { model = glm::mat4(1.0f); model = glm::translate(model, it->second); shader_cube->setMat4("model", model); cube->DrawVegetation(); } movement(); }
效果图: