opengl学习笔记2-4-动画效果

本文通过一个简单的OpenGL动画示例,介绍了如何使用glut库创建动画效果,并探讨了OpenGL的基础概念及其实现原理。代码示例展示了如何移动并绘制矩形。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本节是对笔记2代码的扩展。利用glut生成简单的动画效果。

最近学习中遇到的几点困惑:

1.OpenGL到底是什么?以SGI的GL三维图形库为基础制定的一个通用共享的开放式三维图形标准。定义上来看,OpenGL只是一个标准。

2.OpenGL如何工作?

3.OpenGL和OpenGL扩展之间的关系?

4.使用OpenGL中某些特定功能编写的效果,被我自己的机子的显卡支持可以运行,在别人的机子上是否无法运行?在Mac, linux上是怎么样解决这个问题的?

·随着学习的深入会搞清楚这些最基本的问题。希望有大神可以指教!


本次的代码如下:

GLfloat x1 = 0.0f;
GLfloat y1 = 0.0f;
GLfloat rsize = 25;

GLfloat xstep = 1.0f;
GLfloat ystep = 1.0f;

GLfloat	width = 0.0f;
GLfloat	height = 0.0f;

void RenderScene(void)
{
	//Using the current color clear the window
	glClear(GL_COLOR_BUFFER_BIT);

	//Set the draw color to red
	glColor3f(1.0f, 0.0f, 0.0f);

	//use the current draw color draw a rectangle
	glRectf(x1, y1, rsize+x1, y1-rsize);

	//Refresh the drawing commands
	glutSwapBuffers();
}

void SetupRC(void)
{
	glClearColor(0.6f, 0.4f, 0.7f, 1.0f);
}

void ChangeSize(GLsizei w, GLsizei h)
{
	//To prevent the dividend is zero
	if (h == 0)
	{
		h = 1;
	}

	glViewport(0, 0, w, h);

	//reset coordinate system
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();

	//build clipping region(left, right, bottom, top, near, far)
	GLfloat aspectRatio = (GLfloat)w/h;
	GLfloat nRange = 100.0f;
	if (w <= h)
	{
		glOrtho(-nRange, nRange, -nRange/aspectRatio, nRange/aspectRatio, 1.0, -1.0);
		width = nRange;
		height = nRange/aspectRatio;
	}
	else
	{
		glOrtho(-nRange*aspectRatio, nRange*aspectRatio, -nRange, nRange, 1.0, -1.0);
		width = nRange*aspectRatio;
		height = nRange;
	}

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
}

void TimerFunction(int value)
{
	if (x1<=-width || x1+rsize>=width)
	{
		xstep = - xstep;
	}
	if(y1 >= height || y1-rsize <= -height)
	{
		ystep = -ystep;
	}

	x1 += xstep;
	y1 += ystep;
	
	//Draw the scene with the new coordinates
	glutPostRedisplay();
	glutTimerFunc(33, TimerFunction, 1);
}

int main(int argc, char* argv[])
{
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGBA);
	glutInitWindowSize(800, 600);
	glutCreateWindow("GLAnimation");
	glutDisplayFunc(RenderScene);
	glutReshapeFunc(ChangeSize);
 	glutTimerFunc(10, TimerFunction, 1);

	SetupRC();
	glutMainLoop();

	return 0;
}
代码运行的结果如下:


本节代码下载地址(visual studio 2012):http://download.youkuaiyun.com/detail/airbigboy/6326567


glut

void glutTimerFunc( unsigned int time, void (* callback)( int ), int value );

time:多长时间后调用回调函数,第二个参数为回调函数的指针,value为TimerFunction的ID

该函数为间隔time时间后(单位为毫秒)调用一次回调函数。所以需要在TimerFunction中每次都调用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值