commit 1c42784c3c3c5db42e097593e2de647fda0e27c5
parent bcdf5c55490c0b00a0f62529509ad35b971bb57e
Author: Matsuda Kenji <info@mtkn.jp>
Date: Fri, 16 Dec 2022 15:16:15 +0900
accurate fps
Diffstat:
M | main.c | | | 32 | +++++++++++++++++++++++++------- |
1 file changed, 25 insertions(+), 7 deletions(-)
diff --git a/main.c b/main.c
@@ -50,7 +50,7 @@ void start_menu(void);
void game_init(void);
void game_play(void);
void end_menu(void);
-void next_tick(void);
+void next_tick(float);
void cleanup(void);
void
@@ -143,7 +143,15 @@ game_init(void)
void
game_play(void)
{
+ long t0, t1, dt;
+ long t2; // for frame count
+ struct timespec ts;
+
game_init();
+
+ clock_gettime(CLOCK_MONOTONIC, &ts);
+ t0 = t2 = ts.tv_nsec;
+
while (next_menu == Game_Play){
while (XPending(display) > 0) {
XEvent event;
@@ -209,14 +217,24 @@ game_play(void)
win_width = window_attributes_return.width;
win_height = window_attributes_return.height;
- next_tick();
+ clock_gettime(CLOCK_MONOTONIC, &ts);
+ t1 = ts.tv_nsec;
+ dt = t1 - t0 > 0 ? t1 - t0 : t1 - t0 + 1000 * 1000 * 1000;
+ while(dt < 1.0/FPS * 1000 * 1000 * 1000){
+ clock_gettime(CLOCK_MONOTONIC, &ts);
+ t1 = ts.tv_nsec;
+ dt = t1 - t0 > 0 ? t1 - t0 : t1 - t0 + 1000 * 1000 * 1000;
+ }
+ next_tick(1.0/FPS);
+ clock_gettime(CLOCK_MONOTONIC, &ts);
+ t0 = ts.tv_nsec;
+ dt = t0 - t2 > 0 ? t0 - t2 : t0 - t2 + 1000 * 1000 * 1000;
+ printf("fps: %f\n", 1.0 / ((double) dt / 1000 / 1000 / 1000));
+ t2 = t0;
XClearArea(display, window, 0, 0, win_width, win_height, False);
XFillRectangle(display, window, gc, square.px, square.py, square.width, square.height);
XDrawString(display, window, fgc, square.px, square.py, "player", 6);
-
- struct timespec timetosleep = {0, 1000*1000*1000/FPS}; //not accurate
- nanosleep(&timetosleep, NULL);
}
}
@@ -227,7 +245,7 @@ end_menu(void)
}
void
-next_tick(void)
+next_tick(float dt)
{
square.vx = 0;
if (key_state[Key_D] == Key_Down)
@@ -240,7 +258,7 @@ next_tick(void)
square.vy = -1000;
}
- obj_next_tick(&square, 1.0/FPS);
+ obj_next_tick(&square, dt);
if (square.px <= 0){
square.px = 0;