代碼:
#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; }
運行結果: