多边形有好多种,下面我们按照形状分类讲解。
直接上代码看看
void myDisplay(void) { glClearColor(0.0, 0.0, 0.0, 0.0); glClear(GL_COLOR_BUFFER_BIT); glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0); glBegin(GL_TRIANGLES); glColor3f(1.0,0.0,0.0); glVertex3f(0.25,0.25,0); glVertex3f(0.75,0.25,0); glVertex3f(0.75,0.75,0); glVertex3f(0.25,0.75,0); glEnd(); glFlush(); }
效果图:
绘制很简单的,需要在glBegin中传入GL_TRIANGLES即可。
但是为了能够暴露出问题,我添加了4个端点。可它只绘制出了前三个,所以请大家注意GL_TRIANGLES是每三个端点组成一个三角形,然后再从第四个端点开始的。
如果端点个数不是3的倍数,那么剩下的端点将被舍弃。
那我们如何绘制第二个端点开始的三角形呢?请使用GL_TRIANGLE_STRIP
上代码看一下:
void myDisplay(void) { glClearColor(0.0, 0.0, 0.0, 0.0); glClear(GL_COLOR_BUFFER_BIT); glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0); glBegin(GL_TRIANGLE_STRIP); glColor3f(1.0,0.0,0.0); glVertex3f(0.25,0.25,0); glVertex3f(0.75,0.25,0); glVertex3f(0.75,0.75,0); glVertex3f(0.25,0.75,0); glEnd(); glFlush(); }效果如下:
好,这样的话,端点123组成了第一个三角形,端点234组成了第二个三角形。
再看一个特殊三角形,先上代码
void myDisplay(void) { glClearColor(0.0, 0.0, 0.0, 0.0); glClear(GL_COLOR_BUFFER_BIT); glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0); glBegin(GL_TRIANGLE_FAN); glColor3f(1.0,0.0,0.0); glVertex3f(0.5,0.5,0); glVertex3f(0.5,0.0,0); glVertex3f(0.8536, 0.1464, 0); glVertex3f(1.0,0.5,0); glVertex3f(0.8536, 0.8536,0); glVertex3f(0.5,1.0,0); glVertex3f(0.1464, 0.8536,0); glVertex3f(0.0,0.5,0); glVertex3f(0.1464,0.1464,0); glVertex3f(0.5,0.0,0); glEnd(); glFlush(); }效果如下:
使用GL_TRIANGLE_FAN参数是将第一个端点作为基点,与后面的两两端点成三角形。
例如123456这六个端点,组成的三角形为123,134,145,156。这样的话,多个三角形就会组成不规则扇形。
看一下代码:
void myDisplay(void) { glClearColor(0.0, 0.0, 0.0, 0.0); glClear(GL_COLOR_BUFFER_BIT); glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0); glBegin(GL_QUADS); glColor3f(1.0,0.0,0.0); glVertex3f(0.25,0.25,0); glVertex3f(0.75,0.25,0); glVertex3f(0.75,0.75,0); glVertex3f(0.25,0.75,0); glVertex3f(1.0,1.0,0); glEnd(); glFlush(); }效果如下:
在glBegin中传入GL_QUADS即可绘制四边形,它与GL_TRIANGLES类似,端点数超过4的倍数部分被忽略掉了。
那么有没有类似GL_TRIANGLE_STRIP的参数来绘制所有端点组成的四边形呢?
请使用GL_QUAD_STRIP,这里要注意的是端点构成向量的方向,否则会造成折面的情况。
看看代码:
void myDisplay(void) { glClearColor(0.0, 0.0, 0.0, 0.0); glClear(GL_COLOR_BUFFER_BIT); glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0); glBegin(GL_POLYGON); glColor3f(1.0,0.0,0.0); glVertex3f(0.25,0.25,0); glVertex3f(0.5,0,0); glVertex3f(0.75,0.25,0); glVertex3f(0.75,0.75,0); glVertex3f(0.25,0.75,0); glEnd(); glFlush(); }效果如下: