Implemented a simple timer

This commit is contained in:
Linus Probert 2017-12-05 08:30:08 +01:00
parent f5a23d6798
commit 50f516ad71
4 changed files with 55 additions and 2 deletions

View File

@ -19,6 +19,7 @@ add_executable(breakhack
src/map
src/map_lua
src/camera
src/timer
)
target_link_libraries(breakhack

View File

@ -10,6 +10,7 @@
#include "camera.h"
#include "map.h"
#include "map_lua.h"
#include "timer.h"
#define SCREEN_WIDTH 1024
#define SCREEN_HEIGHT 768
@ -123,10 +124,11 @@ static
void run()
{
bool quit = false;
Timer* fpsTimer = timer_create();
while (!quit)
{
int ticks = SDL_GetTicks();
timer_start(fpsTimer);
quit = handle_events();
@ -137,10 +139,13 @@ void run()
SDL_RenderPresent(gRenderer);
ticks = SDL_GetTicks() - ticks;
int ticks = timer_get_ticks(fpsTimer);
if (ticks < 1000/60)
SDL_Delay((1000/60) - ticks);
timer_stop(fpsTimer);
}
timer_destroy(fpsTimer);
}
static

33
src/timer.c Normal file
View File

@ -0,0 +1,33 @@
#include <SDL2/SDL.h>
#include "util.h"
#include "timer.h"
Timer* timer_create()
{
Timer *t = ec_malloc(sizeof(Timer));
t->startTime = 0;
return t;
}
void timer_start(Timer *t)
{
t->startTime = SDL_GetTicks();
}
void timer_stop(Timer *t)
{
t->startTime = 0;
}
unsigned int timer_get_ticks(Timer *t)
{
if (!t->startTime)
return 0;
return SDL_GetTicks() - t->startTime;
}
void timer_destroy(Timer *t)
{
free(t);
}

14
src/timer.h Normal file
View File

@ -0,0 +1,14 @@
#ifndef TIMER_H_
#define TIMER_H_
typedef struct {
unsigned int startTime;
} Timer;
Timer* timer_create();
void timer_start(Timer*);
void timer_stop(Timer*);
unsigned int timer_get_ticks(Timer*);
void timer_destroy(Timer*);
#endif // TIMER_H_