今天将继续修改OpenGL基础知识(三)中的例子,并进行了一些简单的动画绘制。在编写代码之前先介绍一下函数glutTimerFunc(unsigned int msecs,void (*func) (int value),int value); 这个函数是GLUT库中的函数,主要功能是再等待msecs秒之后,执行func函数,并且可以通过value向这个函数传递参数。
程序代码如下:
#include <GL/glut.h>
//方块初始化
GLfloat x1 = 0.0f;
GLfloat y1 = 0.0f;
GLfloat rsize = 25;
//x轴方向上移动的距离
GLfloat xstep = 1.0f;
//y轴方向上移动的距离
GLfloat ystep = 1.0f;
//窗口宽高变化
GLfloat windowWidth;
GLfloat windowHeight;
void RenderScene(void)
{
glClear(GL_COLOR_BUFFER_BIT); //清除颜色
glColor3f(1.0f,0.0f,0.0f); //设置颜色为红色
glRectf(x1,y1,x1+rsize,y1-rsize); //绘制边长为50的矩形
glutSwapBuffers(); //刷新
}
void TimerFunction(int value)
{
if(x1 > windowWidth-rsize || x1 < -windowWidth)
xstep = -xstep;
if(y1 > windowHeight || y1 < windowHeight+rsize)
ystep = -ystep;
x1 += xstep;
y1 += ystep;
if(x1 > (windowWidth-rsize+xstep))
x1 = windowWidth-rsize-1;
else if(x1 < -(windowWidth+xstep))
x1 = -windowWidth - 1;
if(y1 > (windowHeight + ystep))
y1 = windowHeight-1;
else if(y1 < -(windowHeight-rsize+ystep))
y1 = -windowHeight+rsize-1;
glutPostRedisplay();
glutTimerFunc(33,TimerFunction, 1);
}
//当窗口大小变化时调用
void ChangeSize(GLsizei w,GLsizei h)
{
GLfloat aspectRatio;
if(0 == h)
h = 1;
//设置视口大小
glViewport(0,0,w,h);
//重置坐标系
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
//建立裁剪区
aspectRatio = (GLfloat)w / (GLfloat)h;
if(w <= h)
glOrtho(-100.0,100.0,-100.0/aspectRatio,100/aspectRatio,1.0,-1.0);
else
glOrtho(-100.0*aspectRatio,100.0*aspectRatio,-100.0,100.0,1.0,-1.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
//设置渲染
void SetupRC(void)
{
glClearColor(0.0f,0.0f,1.0f,1.0f);
}
int main(int argc,char* argv[])
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutCreateWindow("OpenGL Sample");
glutDisplayFunc(RenderScene);
glutReshapeFunc(ChangeSize);
glutTimerFunc(33,TimerFunction,1);
SetupRC();
glutMainLoop();
return 0;
}
以下是截图:
以上程序展示的是一个运动的正方形。
......