OpenGL基础知识(四)

今天将继续修改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;
}

 

以下是截图:

以上程序展示的是一个运动的正方形。

 

......睡觉

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值