Advertisement
Guest User

Untitled

a guest
Nov 23rd, 2014
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.66 KB | None | 0 0
  1. // Fixed tickrate gameloop
  2. // Loops through Input and Update at fixed intervals, renders when possible
  3. // Game updated at fixed times, FPS can vary, and will not affect game speed
  4. void Engine::mainloop()
  5. {
  6.     sf::Clock clock;
  7.  
  8.     double previous = clock.getElapsedTime().asSeconds();
  9.     double metricsCounter = previous;
  10.     double accumulator = 0.0;
  11.  
  12.     uint16_t tickCounter = 0;
  13.     uint16_t frameCounter = 0;
  14.  
  15.     while (_isRunning)
  16.     {
  17.         double current = clock.getElapsedTime().asSeconds();
  18.         // calculate time since last frame
  19.         double elapsed = current - previous;
  20.         metricsCounter += elapsed;
  21.        
  22.         // set previous frame time as now (ready to render a now frame)
  23.         previous = current;
  24.        
  25.         // add cycle duration to the accumulator.
  26.         // this is the update time + render time from previous cycle
  27.         accumulator += elapsed;
  28.  
  29.         // when 1 second has passed, reset metrics and timer
  30.         if (metricsCounter >= 1.0)
  31.         {
  32. #ifdef _DEBUG
  33.             // if we're debugging, set window title as the metrics display
  34.             std::string title =
  35.                 " FPS: " + std::to_string(frameCounter) +
  36.                 " TickRate: " + std::to_string(tickCounter) +
  37.                 " Duration: " + std::to_string(clock.getElapsedTime().asSeconds());
  38.            
  39.             _window.setTitle(title);
  40. #endif
  41.             metricsCounter = 0.0;
  42.             frameCounter = tickCounter = 0;
  43.         }
  44.  
  45.         // while accumulator larger than current game tickrate duration, do update
  46.         while (accumulator >= GAMETICK_DURATION_MS)
  47.         {
  48.             processInput();
  49.             update(GAMETICK_DURATION_MS);
  50.             tickCounter++;
  51.             accumulator -= GAMETICK_DURATION_MS;
  52.         }
  53.  
  54.         // Rendering section. Render a frame, then increment frame to FPS counter
  55.         render();
  56.         frameCounter++;
  57.     }
  58.     _window.close();   
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement