1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | #include<glut.h> #include<math.h> #include<gl.h> GLfloat rotf = 0.0f; void myDisplay(void) { glClearColor(1,1,1,1); glClear(GL_COLOR_BUFFER_BIT); glColor3f(0,0,1); glRotatef(rotf,0.0f,1.0f,0.0f); glutWireTeapot(0.5); glFlush(); } void TimerFunction(int p) { rotf-=0.1; glutPostRedisplay(); glutTimerFunc(33,TimerFunction,0); } int main(int argc, char** argv) { glutInit(&argc,argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA); glutInitWindowPosition(100, 100); glutInitWindowSize(400, 400); glutCreateWindow("OpenGL APP"); glutDisplayFunc(&myDisplay); glutTimerFunc(33, TimerFunction, 1); glutMainLoop(); return 0; } |
这个程序想达成的目的就是画个茶壶,让他自己在那沿着Y轴转动。出现的问题是转速越来越快。
解决办法是:
1 2 3 4 5 6 7 8 9 10 11 | void myDisplay(void) { glClearColor(1,1,1,1); glClear(GL_COLOR_BUFFER_BIT); glPushMatrix(); glRotatef(rotf,0.0f,1.0f,0.0f); glColor3f(0,0,1); glutWireTeapot(0.5); glPopMatrix; glFlush(); } |
在显示程序段加入矩阵堆栈,使得每次渲染前,茶壶的初始矩阵被压入堆栈,起到保护初始状态的作用,同时每一个循环中旋转角度增加,每次渲染事glRotatef()函数的第一个参数增大,实现旋转效果。
另外一个解决办法则是将计时器函数中的旋转角度变化去掉,在定义时将旋转角度设为一常量,并不使用矩阵堆栈,则可以实现匀速转动。
代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | #include<glut.h> #include<math.h> #include<gl.h> GLfloat rotf = 1.0f; void myDisplay(void) { glClearColor(1,1,1,1); glClear(GL_COLOR_BUFFER_BIT); glRotatef(rotf,0.0f,1.0f,0.0f); glColor3f(0,0,1); glutWireTeapot(0.5); glFlush(); } void TimerFunction(int p) { glutPostRedisplay(); glutTimerFunc(33,TimerFunction,1); } int main(int argc, char** argv) { glutInit(&argc,argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA); glutInitWindowPosition(100, 100); glutInitWindowSize(400, 400); glutCreateWindow("OpenGL APP"); glutDisplayFunc(&myDisplay); glutTimerFunc(33, TimerFunction,1); glutMainLoop(); return 0; } |
根本 就没有 绕 Y轴旋转 就是一直 在哪儿 刷新重画…..