OpenGL——旋转的六边形(动画)
代码:
#include<iostream> #include <math.h> #include<Windows.h> #include <GL/glut.h> using namespace std; const double TWO_PI = 6.2831853; GLsizei winWidth = 500, winHeight = 500; GLuint regHex; static GLfloat rotTheta; class scrPt { public: GLint x, y; }; void init() { scrPt hexVertex; GLdouble hexTheta; glClearColor(1.0, 1.0, 1.0, 0.0); //创建1个显示列表 regHex = glGenLists(1); //编译显示列表 glNewList(regHex, GL_COMPILE); glColor3f(209.0 / 255.0, 73.0 / 255.0, 78.0 / 255.0); glBegin(GL_POLYGON); for (GLint k = 0; k < 6; k++) { hexTheta = TWO_PI * k / 6; hexVertex.x = 150 + 100 * cos(hexTheta); hexVertex.y = 150 + 100 * sin(hexTheta); glVertex2i(hexVertex.x, hexVertex.y); } glEnd(); glEndList(); } void displayHex() { glClear(GL_COLOR_BUFFER_BIT); glPushMatrix(); //旋转操作 glRotatef(rotTheta, 0.0, 0.0, 1.0); //执行显示列表 glCallList(regHex); glPopMatrix(); //互换缓存 glutSwapBuffers(); glFlush(); } //计算增加的旋转角度 void rotateHex() { rotTheta += 3.0; if (rotTheta > 360.0) { rotTheta -= 360.0; } //标记当前窗口需要重新绘制 //通过glutMainLoop下一次循环时,窗口显示将被回调以重新显示窗口的正常面板 glutPostRedisplay(); } void winReshapeFcn(GLint newWidth, GLint newHeight) { glViewport(0, 0, (GLsizei)newWidth, (GLsizei)newHeight); glMatrixMode(GL_PROJECTION); //重置当前指定的矩阵为单位矩阵,相当于复位操作 glLoadIdentity(); gluOrtho2D(-320.0, 320.0, -320.0, 320.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glClear(GL_COLOR_BUFFER_BIT); } void mouseFcn(GLint button, GLint action, GLint x, GLint y) { switch (button) { case GLUT_LEFT_BUTTON: //鼠标左键,开始旋转 if (action == GLUT_DOWN) { //全局的回调函数,如果启用则rotateHex会被不断调用,直到有窗口事件发生 glutIdleFunc(rotateHex); } break; case GLUT_RIGHT_BUTTON: //鼠标右键,停止旋转 if (action == GLUT_DOWN) { //参数为NULL说明不改变 glutIdleFunc(NULL); } break; defalut: break; } } int main(int argc, char* argv[]) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE); glutInitWindowPosition(100, 100); glutInitWindowSize(winWidth, winHeight); glutCreateWindow("第一个动画程序"); init(); glutDisplayFunc(displayHex); glutReshapeFunc(winReshapeFcn); glutMouseFunc(mouseFcn); glutMainLoop(); system("pause"); return 0; }
运行结果: