#include<stdio.h>
#include<GL/glut.h>
#include<math.h>
#define PI 3.1415926
GLfloat t=0.0;
GLfloat theta=0.0;
void init(){
glClearColor(1.0f,1.0f,1.0f,1.0f);
glShadeModel(GL_PROJECTION);
gluOrtho2D(0.0,800.0,0.0,400.0);
glClear(GL_COLOR_BUFFER_BIT);
}
void drawcircle(double x,double y,double r){ //画车轮
glBegin(GL_LINE_LOOP);
for(int i=0;i<30;i++){
double delta=2*PI*i/30;
glColor3f(0,1,0);
glVertex2f(x+r*cos(delta+theta),y+r*sin(delta+theta)); //车轮外圈
glVertex2f(x,y);
glVertex2f(x+r*cos(delta+theta),y+r*sin(delta+theta)); //车轴
}
glEnd();
}
void drawBicycle(double x,double y){
glLineWidth(10.0); //地面
glBegin(GL_QUADS);
glColor3f(0.0,0.0,0.0);
glVertex2f(0.0,60.0);
glVertex2f(0.0,0.0);
glVertex2f(1200.0,0.0);
glVertex2f(1200.0,60.0);
glEnd();
glTranslatef(t, 0.0f, 0.0f);
glLineWidth(3.0);
glBegin(GL_LINES); //车横梁
glColor3f(0.0,0.0,1.0);
glVertex2f(30.0+x,30.0+y);
glVertex2f(130.0+x,30.0+y);
glEnd();
glBegin(GL_LINES); //车座
glVertex2f(70.0+x,30.0+y);
glVertex2f(70.0+x,60.0+y);
glEnd();
glBegin(GL_LINES);
glColor3f(1.0,0.0,0.0);
glVertex2f(62.5+x,60.0+y);
glVertex2f(77.5+x,60.0+y);
glEnd();
glBegin(GL_LINES); //车把
glColor3f(0.0,0.0,1.0);
glVertex2f(90.0+x,30.0+y);
glVertex2f(90.0+x,70.0+y);
glEnd();
glBegin(GL_LINES);
glColor3f(0.0,0.0,0.0);
glVertex2f(82.5+x,70.0+y);
glVertex2f(97.5+x,70.0+y);
glVertex2f(82.5+x,70.0+y);
glVertex2f(75.5+x,72.0+y);
glVertex2f(97.5+x,70.0+y);
glVertex2f(87.5+x,72.5+y);
glEnd();
drawcircle(30+x,30+y,30); //后车轮
drawcircle(130+x,30+y,30); //前车轮
theta+=30.0f;
if( theta > 360.0f)
theta = 0.0f; //车轮旋转变化
t+=0.05f;
if( t > 800.0f)
t = 0.0f; //车身平移变化
glutPostRedisplay();
}
void display(){
glClear(GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
drawBicycle(0,50); //小车的位置可调
glFlush();
glutSwapBuffers();
}
void reshape(int w, int h)
{
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0,800.0,0.0,400.0);
glClear(GL_COLOR_BUFFER_BIT);
}
int main(int argc, char** argv){
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB);
glutInitWindowSize(1200,600);
glutCreateWindow("自行车");
glutReshapeFunc(reshape);
glutDisplayFunc(display);
init();
glutMainLoop();
return 0;
}