3c9be9bfcb1fe1b27ce2e7b2f864bbff2079af4f
[zeRace] / car.c
1 #include "car.h"
2
3 #define COEFF 1
4
5 void move_car(struct _car *car,int keys,SDL_Surface *fun)
6 {
7   Uint32 c,r,g,b;
8   
9   /* reset flags */
10   car->lapflag=0;
11   car->crashflag=0;
12   
13   /* get the pixel color under the center of car in the function map */
14   c=getpixel(fun,car->x,car->y);
15   /* red layer (checkpoints) */
16   r=(c>>RSHIFT)&0xff;
17   /* green layer (road quality) */
18   g=(c>>GSHIFT)&0xff;
19   /* blue layer (grip) */
20   b=(c>>BSHIFT)&0xff;
21
22   if (keys & 8) /* up */
23     car->speed+=0.01*2*COEFF;
24   if (keys & 4) /* down */
25     car->speed-=0.01*COEFF;
26   if (keys & 2) /* left */
27   {
28     if (car->speed<0)
29       car->angle+=0.01*(255-b)/255*COEFF;
30     else
31       car->angle-=0.01*(255-b)/255*COEFF;
32   }
33   if (keys & 1) /* right */
34   {
35     if (car->speed<0)
36       car->angle-=0.01*(255-b)/255*COEFF;
37     else
38       car->angle+=0.01*(255-b)/255*COEFF;
39   }
40   
41   /* limit angle between 0 and 2*pi */
42   if (car->angle<0) car->angle+=2*M_PI;
43   if (car->angle>2*M_PI) car->angle-=2*M_PI;
44   
45   /* update the speed depending on the road quality */
46   car->speed-=car->speed*(255-g)/1000;
47  
48   /* if it is a wall we move back to the last position */
49   if (g==0)
50   {
51     car->x=car->ox;
52     car->y=car->oy;
53     car->crashflag=1;
54   }
55   
56   /* save the old position and compute the new one */
57   car->ox=car->x;
58   car->oy=car->y;
59   car->speed*=0.995;
60   car->x-=cos(car->angle)*car->speed;
61   car->y-=sin(car->angle)*car->speed;
62   
63   /* collision with the border of the screen */
64   if (car->x<car->w/2 || car->x>fun->w-car->w/2 || car->y<car->h/2 || car->y>fun->h-car->h/2)
65   {
66     car->x=car->ox;
67     car->y=car->oy;
68     car->speed=0;
69     car->crashflag=1;
70   }
71   
72   /* if we are on the next checkpoint, validate it (no missing allowed) */
73   if (r/8==car->lastcheck+1) car->lastcheck++;
74   /* if we validate all and start over, we complete a turn */
75   if (r/8==0 && car->lastcheck==31)
76   {
77     /* reset turn variables */
78     car->lastcheck=0;
79     car->lap++;
80     car->lapflag=1;
81   }
82   
83   return;
84 }