使用GL_LINE_LOOP绘制3D立方体失败,求解决方案
OpenGL GL_LINE_LOOP绘制立方体出错的解决办法
我尝试用OpenGL的GL_LINE_LOOP绘制3D立方体,但无法得到正确的立方体形状,当前输出效果如下:
我的实现代码:
void cube1() { glBegin(GL_LINE_LOOP); //Cube1 //Face1 glColor3f(1.0, 0.0, 0.0); glVertex3f(-0.1, 0, 0); glVertex3f(0.4, 0, 0); glVertex3f(0.4, -0.3, 0); glVertex3f(-0.1, -0.3, 0); //Face2 glColor3f(1.0, 1.0, 0.0); glVertex3f(-0.1, -0.3, 0); glVertex3f(-0.1, -0.3, 1); glVertex3f(-0.1, 0, 1); glVertex3f(-0.1, 0, 0); //Face3 glColor3f(1.0, 0.0, 1.0); glVertex3f(-0.1, 0, 0); glVertex3f(-0.1, 0, 1); glVertex3f(0.4, 0, 1); glVertex3f(0.4, 0, 0); //Face4 glColor3f(0.0, 1.0, 1.0); glVertex3f(0.4, 0, 0); glVertex3f(0.4, 0, 1); glVertex3f(0.4, -0.3, 1); glVertex3f(0.4, -0.3, 0); //Face5 glColor3f(0.0, 1.0, 0.0); glVertex3f(0.4, -0.3, 0); glVertex3f(-0.1, -0.3, 0); glVertex3f(-0.1, -0.3, 1); glVertex3f(0.4, -0.3, 1); //Face6 glColor3f(0.0, 0.0, 1.0); glVertex3f(0.4, -0.3, 1); glVertex3f(-0.1, -0.3, 1); glVertex3f(-0.1, 0, 1); glVertex3f(0.4, 0, 1); glEnd(); }
问题原因
GL_LINE_LOOP的作用是将所有连续传入的顶点连接成一个单一的闭合折线环。你现在把6个面的所有顶点都放在同一个glBegin(GL_LINE_LOOP)和glEnd()之间,导致OpenGL会把第一个面的最后一个顶点和第二个面的顶点继续连接,最终形成的是一个混乱的长线环,而不是每个面独立的闭合线框。
解决方法
给每个立方体的面单独创建一个GL_LINE_LOOP,也就是每个面都用glBegin(GL_LINE_LOOP)和glEnd()包裹起来,让每个面都是独立的闭合线框。修改后的代码如下:
void cube1() { //Face1 glBegin(GL_LINE_LOOP); glColor3f(1.0, 0.0, 0.0); glVertex3f(-0.1, 0, 0); glVertex3f(0.4, 0, 0); glVertex3f(0.4, -0.3, 0); glVertex3f(-0.1, -0.3, 0); glEnd(); //Face2 glBegin(GL_LINE_LOOP); glColor3f(1.0, 1.0, 0.0); glVertex3f(-0.1, -0.3, 0); glVertex3f(-0.1, -0.3, 1); glVertex3f(-0.1, 0, 1); glVertex3f(-0.1, 0, 0); glEnd(); //Face3 glBegin(GL_LINE_LOOP); glColor3f(1.0, 0.0, 1.0); glVertex3f(-0.1, 0, 0); glVertex3f(-0.1, 0, 1); glVertex3f(0.4, 0, 1); glVertex3f(0.4, 0, 0); glEnd(); //Face4 glBegin(GL_LINE_LOOP); glColor3f(0.0, 1.0, 1.0); glVertex3f(0.4, 0, 0); glVertex3f(0.4, 0, 1); glVertex3f(0.4, -0.3, 1); glVertex3f(0.4, -0.3, 0); glEnd(); //Face5 glBegin(GL_LINE_LOOP); glColor3f(0.0, 1.0, 0.0); glVertex3f(0.4, -0.3, 0); glVertex3f(-0.1, -0.3, 0); glVertex3f(-0.1, -0.3, 1); glVertex3f(0.4, -0.3, 1); glEnd(); //Face6 glBegin(GL_LINE_LOOP); glColor3f(0.0, 0.0, 1.0); glVertex3f(0.4, -0.3, 1); glVertex3f(-0.1, -0.3, 1); glVertex3f(-0.1, 0, 1); glVertex3f(0.4, 0, 1); glEnd(); }
另外,也可以考虑使用GL_LINES来绘制立方体的所有棱边,但每个棱需要两个顶点,不过用GL_LINE_LOOP给每个面单独绘制是更直观的方式。
内容的提问来源于stack exchange,提问作者Alexander
相关产品推荐
相关产品推荐

