Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Links = https://gamedev.stackexchange.com/questions/163477/how-can-i-avoid-jittery-motion-in-sdl2
- struct Timer
- {
- Uint64 previous_ticks{};
- float elapsed_seconds{};
- void tick()
- {
- const Uint64 current_ticks{ SDL_GetPerformanceCounter() };
- const Uint64 delta{ current_ticks - previous_ticks };
- previous_ticks = current_ticks;
- static const Uint64 TICKS_PER_SECOND{ SDL_GetPerformanceFrequency() };
- elapsed_seconds = delta / static_cast<float>(TICKS_PER_SECOND);
- }
- };
- int main()
- {
- /*--------------Game loop--------------*/
- // Timing constants
- const int UPDATE_FREQUENCY{ 60 };
- const float CYCLE_TIME{ 1.0f / UPDATE_FREQUENCY };
- // System timing
- static Timer system_timer;
- float accumulated_seconds{ 0.0f };
- while (is_running)
- {
- // Update clock
- system_timer.tick();
- accumulated_seconds += system_timer.elapsed_seconds;
- /*--------------Event loop--------------*/
- /* ... */
- // Cap the framerate
- if (std::isgreater(accumulated_seconds, CYCLE_TIME))
- {
- // Reset the accumulator
- accumulated_seconds = -CYCLE_TIME;
- /*--------------Physics loop--------------*/
- static Timer physics_timer;
- physics_timer.tick();
- bot.position.x += bot.direction.x * bot.speed * physics_timer.elapsed_seconds;
- bot.position.y += bot.direction.y * bot.speed * physics_timer.elapsed_seconds;
- // Screen coordinate translations
- /* ... */
- ground.update();
- bot.update();
- // Camera
- /* ... */
- /*--------------Rendering loop--------------*/
- SDL_RenderClear(ren);
- ground.draw(ren);
- bot.draw(ren);
- SDL_RenderPresent(ren);
- /*--------------Todo: Animation loop--------------*/
- static Timer animation_timer;
- animation_timer.tick();
- /* ... */
- }
- }
- // Clean up used resources
- /* ... */
- SDL_Quit();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement