A switch()
на основе state
с соответствующими glClearColor()
/ glColor3f()
вызовами будет работать:
void drawScene()
{
switch( state )
{
case 0: glClearColor( 0.0, 0.0, 0.0, 1.0 ); break;
case 1: glClearColor( 0.0, 1.0, 0.0, 1.0 ); break;
case 2: glClearColor( 0.2, 0.0, 0.0, 1.0 ); break;
case 3: glClearColor( 0.0, 0.0, 1.0, 1.0 ); break;
}
glClear( GL_COLOR_BUFFER_BIT );
...
Демонстрация:
Все вместе:
#include <cstdio>
#include <GL/glut.h>
#include <cmath>
float squareX = 162.0f;
float squareY = 0.0f;
float squareZ = 0.0f;
void drawShape( void )
{
float width = 58.0f;
float height = 40.0f;
glTranslatef( squareX, squareY, squareZ );
glBegin( GL_POLYGON );
glColor3f( 1.0, 0.0, 0.0 );
glVertex2f( 0, 0 );
glVertex2f( width, 0 );
glVertex2f( width, height );
glVertex2f( 0, height );
glVertex2f( 0, 0 );
glEnd();
}
// called when the window is resized
void handleResize( int w, int h )
{
glViewport( 0, 0, w, h );
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
glOrtho( 0.0f, (float)w, 0.0f, (float)h, -1.0f, 1.0f );
}
int state = 1;
void drawScene()
{
switch( state )
{
case 0: glClearColor( 0.0, 0.0, 0.0, 1.0 ); break;
case 1: glClearColor( 0.0, 1.0, 0.0, 1.0 ); break;
case 2: glClearColor( 0.2, 0.0, 0.0, 1.0 ); break;
case 3: glClearColor( 0.0, 0.0, 1.0, 1.0 ); break;
}
glClear( GL_COLOR_BUFFER_BIT );
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
glPushMatrix();
drawShape();
glPushMatrix();
glFlush();
glutSwapBuffers();
glutPostRedisplay();
}
// make the square go up
void update( int value )
{
// 1 : move up
if( state == 1 )
{
squareY += 1.0f;
if( squareY > 400.0 )
{
state = 2;
squareX = 0.0f;
squareY = 180.0f;
}
}
// 2 : move right
else if( state == 2 )
{
squareX += 1.0f;
if( squareX > 400.0 )
{
state = 3;
squareX = 180.0f;
squareY = 400.0f;
}
}
// 3 : move down
else if( state == 3 )
{
squareY -= 1.0f;
if( squareY < 0.0 )
{
state = 0;
}
}
glutPostRedisplay();
glutTimerFunc( 25, update, 0 );
}
int main( int argc, char** argv )
{
glutInit( &argc, argv );
glutInitDisplayMode( GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH );
glutInitWindowSize( 400, 400 );
glutCreateWindow( "Moving Square" );
glutDisplayFunc( drawScene );
glutReshapeFunc( handleResize );
glutTimerFunc( 25, update, 0 );
glutMainLoop();
return( 0 );
}