opengl绘制立方体并旋转
时间: 2023-08-25 22:05:46 浏览: 108
下面是一个使用 OpenGL 绘制立方体并旋转的示例代码:
```c++
#include <GL/glut.h>
GLfloat angle = 0.0f; // 旋转角度
// 绘制立方体
void drawCube()
{
glBegin(GL_QUADS);
// 前面
glColor3f(1.0f, 0.0f, 0.0f);
glVertex3f(-1.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);
// 后面
glColor3f(0.0f, 1.0f, 0.0f);
glVertex3f(-1.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);
// 左面
glColor3f(0.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);
glVertex3f(-1.0f, -1.0f, -1.0f);
// 右面
glColor3f(1.0f, 1.0f, 0.0f);
glVertex3f(1.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);
// 上面
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);
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);
glVertex3f(-1.0f, -1.0f, 1.0f);
glEnd();
}
// 显示回调函数
void display()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0.0f, 0.0f, -5.0f); // 平移
glRotatef(angle, 1.0f, 1.0f, 0.0f); // 绕 x 和 y 轴旋转
drawCube();
glutSwapBuffers();
}
// 定时器回调函数,每隔一段时间更新角度并重绘
void timer(int value)
{
angle += 1.0f;
if (angle >= 360.0f) {
angle -= 360.0f;
}
glutPostRedisplay();
glutTimerFunc(16, timer, 0);
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(640, 480);
glutCreateWindow("OpenGL Cube");
glEnable(GL_DEPTH_TEST);
glutDisplayFunc(display);
glutTimerFunc(0, timer, 0);
glutMainLoop();
return 0;
}
```
在 `drawCube()` 函数中绘制了一个立方体,使用 `glTranslatef()` 和 `glRotatef()` 进行平移和旋转,然后在 `display()` 函数中进行绘制,最后在 `timer()` 函数中更新角度并重绘。
阅读全文