Last active
November 14, 2021 00:04
-
-
Save oreyg/13069248a9f7ffe3962d882cf9123c03 to your computer and use it in GitHub Desktop.
Example of game engine tick loop
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static constexpr uint64_t g_fixed_frame_rate = 60; | |
static constexpr double g_fixed_delta_time = 1.0 / g_fixed_frame_rate; | |
// Time counters | |
uint64_t m_start_tick = 0; | |
uint64_t m_prev_tick = 0; | |
uint64_t m_delta_tick = 0; | |
// Last processed frame number | |
uint64_t m_fixed_last_frame = 0; | |
void engine_tick(void) | |
{ | |
const uint64_t perf_freq = SDL_GetPerformanceFrequency(); | |
const uint64_t perf_tick = SDL_GetPerformanceCounter(); | |
const uint64_t delta_tick = perf_tick - m_prev_tick; | |
const float delta_time = delta_tick / (float)perf_freq; | |
constexpr float e = 1e-15F; | |
if (delta_time > e) | |
{ | |
update(delta_time); | |
} | |
const uint64_t fixed_tick_duration = (uint64_t)(g_fixed_delta_time * perf_freq); | |
const uint64_t target_frame = (perf_tick - m_start_tick) / fixed_tick_duration; | |
while (m_fixed_last_frame < target_frame) | |
{ | |
++m_fixed_last_frame; | |
fixed_update(); | |
} | |
m_prev_tick = perf_tick; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment