用opengl绘制一个旋转的三棱锥,给出代码
时间: 2024-05-03 07:16:28 浏览: 210
opengl 绘制 棱锥
5星 · 资源好评率100%
以下是使用 OpenGL 绘制旋转的三棱锥的代码:
```c++
#include <GL/glut.h>
GLfloat angle = 0.0f;
void renderScene(void) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glTranslatef(0.0f, 0.0f, -5.0f);
glRotatef(angle, 1.0f, 1.0f, 1.0f);
glBegin(GL_TRIANGLES);
// 绘制三棱锥的六个面
glColor3f(1.0f, 0.0f, 0.0f);
glVertex3f(0.0f, 1.0f, 0.0f);
glVertex3f(-1.0f, -1.0f, 1.0f);
glVertex3f(1.0f, -1.0f, 1.0f);
glColor3f(0.0f, 1.0f, 0.0f);
glVertex3f(0.0f, 1.0f, 0.0f);
glVertex3f(1.0f, -1.0f, 1.0f);
glVertex3f(1.0f, -1.0f, -1.0f);
glColor3f(0.0f, 0.0f, 1.0f);
glVertex3f(0.0f, 1.0f, 0.0f);
glVertex3f(1.0f, -1.0f, -1.0f);
glVertex3f(-1.0f, -1.0f, -1.0f);
glColor3f(1.0f, 1.0f, 0.0f);
glVertex3f(0.0f, 1.0f, 0.0f);
glVertex3f(-1.0f, -1.0f, -1.0f);
glVertex3f(-1.0f, -1.0f, 1.0f);
glColor3f(1.0f, 0.0f, 1.0f);
glVertex3f(-1.0f, -1.0f, 1.0f);
glVertex3f(1.0f, -1.0f, 1.0f);
glVertex3f(1.0f, -1.0f, -1.0f);
glColor3f(0.0f, 1.0f, 1.0f);
glVertex3f(1.0f, -1.0f, -1.0f);
glVertex3f(-1.0f, -1.0f, -1.0f);
glVertex3f(-1.0f, -1.0f, 1.0f);
glEnd();
angle += 0.1f;
glutSwapBuffers();
}
int main(int argc, char **argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);
glutInitWindowPosition(100, 100);
glutInitWindowSize(320, 320);
glutCreateWindow("OpenGL Demo");
glutDisplayFunc(renderScene);
glutIdleFunc(renderScene);
glEnable(GL_DEPTH_TEST);
glutMainLoop();
return 0;
}
```
这段代码使用 GLUT 库来创建 OpenGL 窗口,然后使用 glBegin 和 glEnd 函数分别开始和结束绘制三角形的过程。在绘制三角形之前,通过 glTranslatef 和 glRotatef 函数分别对三棱锥进行平移和旋转。最后,使用 glutIdleFunc 函数来定义一个循环,在循环中不断地更新旋转角度,并调用 glutSwapBuffers 函数来更新窗口。
阅读全文