I am trying to move a ball using time. The ball must move 5 pixel per second.
In my code the ball is moving faster. Why is it moving faster? What is wrong with my code?
#include <allegro.h>
#include <cstdlib>
#include <time.h>
int ball_x = 320;
int ball_y = 240;
int ball_tx;
int ball_ty;
BITMAP *buffer; //This will be our temporary bitmap for double buffering
float timer(){
clock_t cur_time,start_time;
cur_time = clock();
start_time = cur_time + 1;
return difftime(start_time,cur_time);
}
void moveBall(){
ball_tx = ball_x;
ball_ty = ball_y;
int speed = timer() * 5;
if(key[KEY_LEFT])ball_x = ball_x - speed;
else if(key[KEY_RIGHT])ball_x = ball_x + speed;
else if(key[KEY_UP])ball_y = ball_y - speed;
else if(key[KEY_DOWN])ball_y = ball_y + speed;
acquire_screen();
textprintf(buffer,font,10,10,makecol(255,255,255),"ball x = %d" "ball y = %d",ball_x,ball_y);
circlefill ( buffer, ball_tx, ball_ty, 5, makecol( 0, 0, 0));
circlefill ( buffer, ball_x, ball_y, 5, makecol( 255, 255, 255));
draw_sprite( screen, buffer, 0, 0);
release_screen();
}
int main(){
allegro_init();
install_keyboard();
set_color_depth(16);
set_gfx_mode( GFX_AUTODETECT_WINDOWED, 640, 480, 0, 0);
buffer = create_bitmap( 640, 480);
while( !key[KEY_ESC]){
moveBall();
}
return 0;
}
END_OF_MAIN();