Le source : AnimationMouvementSurCarre.cpp
/* Auteur: Nicolas JANEY */
/* nicolas.janey@univ-fcomte.fr */
/* Octobre 2006 */
/* Animation par deplacement sur un carre virtuel */
/* en C + OpenGL + GLUT */
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <GL/glut.h>
#include <GL/gl.h>
#include <GL/glu.h>
static float distanceParcourue = 0.0F;
static float delta = 0.022F;
static float c = 6.0F;
static int animation = 1;
static int l = 1;
void idle(void) {
distanceParcourue += delta ;
glutPostRedisplay();
}
void key(unsigned char key,int x,int y) {
switch ( key ) {
case 's' : delta = -delta;
break;
case 'a' : delta /= 1.01F;
break;
case 'A' : delta *= 1.01F;
break;
case ' ' : animation = !animation ;
glutIdleFunc((animation) ? idle : NULL);
break;
case 0x0D : l = !l ;
glutPostRedisplay();
break;
case 0x1B : exit(0); }
}
void reshape(int tx,int ty) {
glViewport(0,0,tx,ty);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(4.5*(double) -tx/ty,4.5*(double) tx/ty,-4.5,4.5,-4.5,4.5) ;
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
float modulo(float a,float b) {
float r = a - floor(a/b)*b;
return(r);
}
void display(void) {
if ( l )
glEnable(GL_LIGHTING);
else
glDisable(GL_LIGHTING);
glClearColor(0.8F,0.8F,0.8F,1.0F) ;
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT) ;
float distance = modulo(distanceParcourue,4*c);
glPushMatrix();
if ( distance < c )
glTranslatef(c/2,c/2-distance,0.0F);
else
if ( distance < 2*c )
glTranslatef(c/2-(distance-c),-c/2,0.0F);
else
if ( distance < 3*c )
glTranslatef(-c/2,-c/2+(distance-2*c),0.0F);
else
glTranslatef(-c/2+(distance-3*c),c/2,0.0F);
glutSolidSphere(1.0,72,72);
glPopMatrix();
glFlush();
glutSwapBuffers();
printf("*");
int error = glGetError();
if ( error != GL_NO_ERROR )
printf("Attention, erreur OpenGL %d\n",error);
}
void init(void) {
GLfloat l_pos[] = { 0.0F,0.0F,1.0F,0.0F };
GLfloat c[4] = { 0.5F,0.2F,0.6F,1.0F };
glMaterialfv(GL_FRONT,GL_DIFFUSE,c);
glLightfv(GL_LIGHT0,GL_POSITION,l_pos);
glEnable(GL_LIGHT0);
glColor4fv(c) ;
glEnable(GL_DEPTH_TEST);
glEnable(GL_NORMALIZE);
}
int main(int argc,char **argv) {
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_RGBA|GLUT_DOUBLE);
glutInitWindowSize(250,250);
glutInitWindowPosition(50,50);
glutCreateWindow("Animation par deplacement");
init();
glutReshapeFunc(reshape);
glutKeyboardFunc(key);
glutIdleFunc(idle);
glutDisplayFunc(display);
glutMainLoop();
return(0);
}