D=(A./B).^n
上面的代码从下至上,从左至右以及从上至下移动一个正方形。背景颜色为蓝色,但是每次碰撞检测后如何更改背景颜色?每次碰撞检测后我要达到的颜色顺序是蓝色,红色和绿色。我已经在背景位置添加了评论。
答案 0 :(得分:1)
一个基于state
的{{3}}并带有适当的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 );
}