1 #include <gl/glut.h> 2 3 float fEarth = 2.0f; //地球绕太阳的旋转角度 4 5 float fMoon = 24.0f; //月球绕地球的旋转角度 6 7 void Init() 8 9 { 10 11 glEnable(GL_DEPTH_TEST); //启用深度测试 12 13 glClearColor(0.0f, 0.0f, 0.0f, 0.8f); //背景为黑色 14 15 } 16 17 void Reshape(int w, int h) 18 19 { 20 21 if (0 == h) 22 23 h = 1; 24 25 glViewport(0, 0, w, h); //设置视区尺寸 26 27 glMatrixMode(GL_PROJECTION); //指定当前操作投影矩阵堆栈 28 29 glLoadIdentity(); //重置投影矩阵 30 31 //指定透视投影的观察空间 32 33 gluPerspective(45.0f, (float)w / (float)h, 1.0f, 1000.0f); 34 35 glMatrixMode(GL_MODELVIEW); 36 37 glLoadIdentity(); 38 39 } 40 41 void Display(void) 42 43 { 44 45 //清除颜色和深度缓冲区 46 47 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); 48 49 glMatrixMode(GL_MODELVIEW); //指定当前操作模型视图矩阵堆栈 50 51 glLoadIdentity(); //重置模型视图矩阵 52 53 glTranslatef(0.0f, 0.0f, -500.0f); //将图形沿z轴负向移动 54 55 glColor3f(1.0f, 0.0f, 0.0f); //画太阳 56 57 glutSolidSphere(50.0f, 20, 20); 58 59 glColor3f(0.0f, 0.0f, 1.0f); 60 61 glRotatef(23.27,0.0,0.0,1.0); //地球与太阳的黄赤交角 62 63 glRotatef(fEarth, 0.0f, 1.0f, 0.0f); 64 65 glTranslatef(200.0f, 0.0f, 0.0f); 66 67 glutSolidSphere(20.0f, 20, 20); //画地球 68 69 glPopMatrix(); 70 71 glPopMatrix(); 72 73 glRotatef(6.0f, 1.0f, 1.0f, 1.0f); 74 75 glRotatef(fMoon, 0.0f, 1.0f, 0.0f); 76 77 glColor3f(1.0f, 1.0f, 0.0f); 78 79 glTranslatef(30.0f, 0.0f, 0.0f); 80 81 glutSolidSphere(5.0f, 20, 20); //画月球 82 83 glLoadIdentity(); 84 85 glFlush(); 86 87 glutSwapBuffers(); 88 89 } 90 91 void myIdle(void) //在空闲时调用,达到动画效果 92 93 { 94 95 fEarth += 0.03f; //增加旋转步长,产生动画效果 96 97 if (fEarth > 360.0f) 98 99 fEarth = 2.0f; 100 101 fMoon += 0.24f; 102 103 if (fMoon > 360.0f) 104 105 fMoon = 24.0f; 106 107 Display(); 108 109 } 110 111 int main(int argc, char *argv[]) 112 113 { 114 115 glutInit(&argc, argv); 116 117 //窗口使用RGB颜色,双缓存和深度缓存 118 119 glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); 120 121 glutInitWindowPosition(100,100); 122 123 glutInitWindowSize(600, 400); 124 125 glutCreateWindow("太阳系动画"); 126 127 glutReshapeFunc(Reshape); 128 129 glutDisplayFunc(Display); 130 131 glutIdleFunc(&myIdle); 132 133 Init(); 134 135 glutMainLoop(); 136 137 return 0; 138 139 }
附上本实验的VC++工程代码(VC++2008)