如何为由OpenGL和GLUT中的键触发的旋转设置动画? [英] How to animate a rotation triggered by a key in OpenGL and GLUT?
本文介绍了如何为由OpenGL和GLUT中的键触发的旋转设置动画?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用C语言中的GLUT在OpenGL中旋转一个简单的多维数据集.当我按下一个键时,旋转就会发生.
I want to rotate a simple cube in OpenGL using GLUT in C. The rotation will occur when I press a key.
如果使用glRotatef(angle, 0.0f, 1.0f, 0.0f)
,则多维数据集将立即旋转而不会显示动画.我想慢慢旋转,所以大约需要2秒钟才能完成旋转.
If I use glRotatef(angle, 0.0f, 1.0f, 0.0f)
the cube will rotate instantly without an animation. I would like to rotate it slowly so it takes about 2 seconds to complete the rotation.
推荐答案
创建一个可切换布尔值的键盘回调和一个用于更新角度的计时器回调:
Create a keyboard callback that toggles a bool and a timer callback that updates an angle:
#include <GL/glut.h>
char spin = 0;
void keyboard( unsigned char key, int x, int y )
{
if( key == ' ' )
{
spin = !spin;
}
}
float angle = 0;
void timer( int value )
{
if( spin )
{
angle += 3;
}
glutTimerFunc( 16, timer, 0 );
glutPostRedisplay();
}
void display()
{
double w = glutGet( GLUT_WINDOW_WIDTH );
double h = glutGet( GLUT_WINDOW_HEIGHT );
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
gluPerspective( 45, w / h, 0.1, 10 );
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
gluLookAt( 2, 2, 2, 0, 0, 0, 0, 0, 1 );
glColor3ub( 255, 0, 0 );
glRotatef( angle, 0, 0, 1 );
glutWireCube( 1 );
glutSwapBuffers();
}
int main( int argc, char **argv )
{
glutInit( &argc, argv );
glutInitDisplayMode( GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE );
glutInitWindowSize( 640, 480 );
glutCreateWindow( "GLUT" );
glutDisplayFunc( display );
glutKeyboardFunc( keyboard );
glutTimerFunc( 0, timer, 0 );
glutMainLoop();
return 0;
}
这篇关于如何为由OpenGL和GLUT中的键触发的旋转设置动画?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文