用c++的OpenGL写一个四个面颜色不同的三棱锥绕轴旋转的代码
时间: 2024-05-15 08:19:07 浏览: 78
好的,下面是代码实现:
```
#include<gl/glut.h>
GLfloat vertices[][3] = { {-1.0,-1.0,-1.0},{1.0,-1.0,-1.0},
{1.0,1.0,-1.0},{-1.0,1.0,-1.0},
{-1.0,-1.0,1.0},{1.0,-1.0,1.0},
{1.0,1.0,1.0},{-1.0,1.0,1.0} };
GLfloat theta[] = { 0.0,0.0,0.0 };
GLint axis = 2;
GLdouble viewer[] = { 0.0,0.0,5.0 };
void polygon(int a, int b, int c, int d)
{
glBegin(GL_QUADS);
glVertex3fv(vertices[a]);
glVertex3fv(vertices[b]);
glVertex3fv(vertices[c]);
glVertex3fv(vertices[d]);
glEnd();
}
void colorcube()
{
glColor3f(1.0,0.0,0.0);
polygon(1,0,3,2);
glColor3f(0.0,1.0,0.0);
polygon(2,3,7,6);
glColor3f(0.0,0.0,1.0);
polygon(3,0,4,7);
glColor3f(1.0,1.0,0.0);
polygon(6,5,1,2);
glColor3f(1.0,0.0,1.0);
polygon(4,5,6,7);
glColor3f(0.0,1.0,1.0);
polygon(5,4,0,1);
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
gluLookAt(viewer[0],viewer[1],viewer[2],0.0,0.0,0.0,0.0,1.0,0.0);
glRotatef(theta[0], 1.0, 0.0, 0.0);
glRotatef(theta[1], 0.0, 1.0, 0.0);
glRotatef(theta[2], 0.0, 0.0, 1.0);
colorcube();
glFlush();
glutSwapBuffers();
}
void myreshape(int w, int h)
{
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if (w <= h)
glOrtho(-2.0, 2.0, -2.0 * (GLfloat)h / (GLfloat)w,
2.0 * (GLfloat)h / (GLfloat)w, -10.0, 10.0);
else
glOrtho(-2.0 * (GLfloat)w / (GLfloat)h,
2.0 * (GLfloat)w / (GLfloat)h, -2.0, 2.0, -10.0, 10.0);
glMatrixMode(GL_MODELVIEW);
}
void spinCube()
{
theta[axis] += 0.1;
if (theta[axis] > 360.0) theta[axis] -= 360.0;
glutPostRedisplay();
}
void mouse(int btn, int state, int x, int y)
{
if (btn == GLUT_LEFT_BUTTON && state == GLUT_DOWN) axis = 0;
if (btn == GLUT_MIDDLE_BUTTON && state == GLUT_DOWN) axis = 1;
if (btn == GLUT_RIGHT_BUTTON && state == GLUT_DOWN) axis = 2;
}
int main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(500, 500);
glutCreateWindow("Colorcube");
glutReshapeFunc(myreshape);
glutDisplayFunc(display);
glutIdleFunc(spinCube);
glutMouseFunc(mouse);
glEnable(GL_DEPTH_TEST);
glutMainLoop();
return 0;
}
```
这是一个基于 OpenGL 的代码实现,可以绘制一个带有不同颜色的四面体,并且可以绕某个轴进行旋转。其中,`colorcube` 函数用于绘制四面体,`display` 函数用于在窗口中显示绘制结果,`spinCube` 函数用于控制旋转,`mouse` 函数用于控制鼠标操作,`myreshape` 函数用于对窗口大小进行适应性的设置。如果需要更加详细的解释,请访问相关学习资源进行学习。
阅读全文