How to animate a rotation triggered by a key in OpenGL and GLUT?

一世执手 提交于 2019-12-13 05:11:12

问题


I want to rotate a simple cube in OpenGL using GLUT in C. The rotation will occur when I press a key.

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.


回答1:


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;
}


来源:https://stackoverflow.com/questions/20396485/how-to-animate-a-rotation-triggered-by-a-key-in-opengl-and-glut

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!