[cc lang=’c’]
#include
#include
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;
}
[/cc]
这个程序想达成的目的就是画个茶壶,让他自己在那沿着Y轴转动。出现的问题是转速越来越快。
解决办法是:
[cc lang=’c’]
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();
}
[/cc]
在显示程序段加入矩阵堆栈,使得每次渲染前,茶壶的初始矩阵被压入堆栈,起到保护初始状态的作用,同时每一个循环中旋转角度增加,每次渲染事glRotatef()函数的第一个参数增大,实现旋转效果。
另外一个解决办法则是将计时器函数中的旋转角度变化去掉,在定义时将旋转角度设为一常量,并不使用矩阵堆栈,则可以实现匀速转动。
代码如下
[cc lang=’c’]
#include
#include
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;
}
[/cc]
近期评论