Advertisement
SilverTES

SDL2 GameLoop

May 5th, 2019
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.15 KB | None | 0 0
  1. // Links = https://gamedev.stackexchange.com/questions/163477/how-can-i-avoid-jittery-motion-in-sdl2
  2.  
  3. struct Timer
  4. {
  5.     Uint64 previous_ticks{};
  6.     float elapsed_seconds{};
  7.  
  8.     void tick()
  9.     {
  10.         const Uint64 current_ticks{ SDL_GetPerformanceCounter() };
  11.         const Uint64 delta{ current_ticks - previous_ticks };
  12.         previous_ticks = current_ticks;
  13.         static const Uint64 TICKS_PER_SECOND{ SDL_GetPerformanceFrequency() };
  14.         elapsed_seconds = delta / static_cast<float>(TICKS_PER_SECOND);
  15.     }
  16. };
  17.  
  18. int main()
  19. {
  20.     /*--------------Game loop--------------*/
  21.     // Timing constants
  22.     const int UPDATE_FREQUENCY{ 60 };
  23.     const float CYCLE_TIME{ 1.0f / UPDATE_FREQUENCY };
  24.     // System timing
  25.     static Timer system_timer;
  26.     float accumulated_seconds{ 0.0f };
  27.     while (is_running)
  28.     {
  29.         // Update clock
  30.         system_timer.tick();
  31.         accumulated_seconds += system_timer.elapsed_seconds;
  32.  
  33.         /*--------------Event loop--------------*/
  34.         /* ... */
  35.  
  36.         // Cap the framerate
  37.         if (std::isgreater(accumulated_seconds, CYCLE_TIME))
  38.         {
  39.             // Reset the accumulator
  40.             accumulated_seconds = -CYCLE_TIME;
  41.  
  42.             /*--------------Physics loop--------------*/
  43.             static Timer physics_timer;
  44.             physics_timer.tick();
  45.  
  46.             bot.position.x += bot.direction.x * bot.speed * physics_timer.elapsed_seconds;
  47.             bot.position.y += bot.direction.y * bot.speed * physics_timer.elapsed_seconds;
  48.  
  49.             // Screen coordinate translations
  50.             /* ... */
  51.  
  52.             ground.update();
  53.             bot.update();
  54.  
  55.             // Camera
  56.             /* ... */
  57.  
  58.             /*--------------Rendering loop--------------*/
  59.             SDL_RenderClear(ren);
  60.             ground.draw(ren);
  61.             bot.draw(ren);
  62.             SDL_RenderPresent(ren);
  63.  
  64.             /*--------------Todo: Animation loop--------------*/
  65.             static Timer animation_timer;
  66.             animation_timer.tick();
  67.  
  68.             /* ... */
  69.         }
  70.     }
  71.  
  72.     // Clean up used resources
  73.     /* ... */
  74.     SDL_Quit();
  75.     return 0;
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement