[OGL][初级]2D的旋转齿轮 (两个齿轮咬合)
来自 www." border="0" />
:D 代码没有优化就送上来了
" border="0" />
程序代码:
#include <stdio.h> #include <stdlib.h> #include <GL/glut.h> #include <time.h> #include <math.h> int winid; float angx=-2.25,angxb=-13.5; //float angx=0.0,angxb=-9.0; void gears(float length,float lenadd,float parts) { float x,y,z,tmplen,i; float maxi=parts; glBegin(GL_LINE_LOOP); for (i=0.0;i<maxi;i+=1.0) { if ((int) i%2==0) { if ((int) (i/2)%2==0) { tmplen=length+8.0; } else { tmplen=length; } } x=(tmplen)*cos(6.28*i/maxi); y=(tmplen)*sin(6.28*i/maxi); glVertex3f(x,y,0.0); } glEnd(); } void display(void) { float x,y,z; static float i,ti,tmplen; float maxi=40.0,length; glClear(GL_COLOR_BUFFER_BIT); glEnable(GL_BLEND); glEnable(GL_LINE_SMOOTH); glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); glLineWidth(2.0); glPushMatrix(); glRotatef(angx,0.0,0.0,1.0); gears(50.0,8.0,80.0); glPopMatrix(); glPushMatrix(); glTranslatef(-80.0,0.0,0.0); glRotatef(-angxb,0.0,0.0,1.0); gears(20.0,8.0,40.0); glPopMatrix(); glFlush(); } void idle(void) { angx+=2.0; angxb+=4.0; usleep(36000); glutPostRedisplay(); } void reshape(int Width,int Height) { float far=200.0; glViewport(0,0,500,500); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(-100,100,-100,100,0,500); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(0.0,0.0,far, 0.0,0.0,0.0, 0.0,1.0,far); } void init(void) { glClearColor(0.0,0.0,0.0,0.0); } void keypress(unsigned char key,int mousex,int mousey) { switch (key) { case 'q': glutDestroyWindow(winid); exit(0); break; case 'a': glutPostRedisplay(); break; } } void keyup(unsigned char key,int mousex,int mousey) { switch (key) { case 'a': break; } } int main(int argc,char *argv[]) { glutInit(&argc,argv); glutInitDisplayMode(GLUT_SINGLE|GLUT_RGBA); glutInitWindowSize(500,500); glutInitWindowPosition(100,100); winid=glutCreateWindow("Press x"); init(); glutReshapeFunc(reshape); glutDisplayFunc(display); glutIdleFunc(idle); glutKeyboardFunc(keypress); glutKeyboardUpFunc(keyup); glutMainLoop(); return 0; }
[ 本帖最后由 if_exist 于 2012-4-2 10:43 编辑 ]