Advertisement
Guest User

Run Loop

a guest
Oct 26th, 2013
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.32 KB | None | 0 0
  1. // Run Method
  2.     boolean isRunning = false;
  3.     // Variables for the FPS and UPS counter
  4.     private int ticks = 0;
  5.     private int frames = 0;
  6.     private int FPS = 0;
  7.     private int UPS = 0;
  8.     public double delta = 0;
  9.     // Used in the "run" method to limit the frame rate to the UPS
  10.     private boolean limitFrameRate = true;
  11.     private boolean shouldRender;
  12.  
  13.     public synchronized void run() {
  14.         long lastTime = System.nanoTime();
  15.         double nsPerTick = 1000000000D / 60D;
  16.  
  17.         long lastTimer = System.currentTimeMillis();
  18.         delta = 0D;
  19.  
  20.         while (isRunning) {
  21.             long now = System.nanoTime();
  22.             delta += (now - lastTime) / nsPerTick;
  23.             lastTime = now;
  24.  
  25.             // If you want to limit frame rate, shouldRender = false
  26.             shouldRender = false;
  27.  
  28.             // If the time between ticks = 1, then various things (shouldRender = true, keeps FPS locked at UPS)
  29.             while (delta >= 1) {
  30.                 ticks++;
  31.                 tick();
  32.                 delta -= 1;
  33.                 shouldRender = true;
  34.             }
  35.  
  36.             if (!limitFrameRate && ticks > 0)
  37.                 shouldRender = true;
  38.  
  39.             // If you should render, render!
  40.             if (shouldRender) {
  41.                 frames++;
  42.                 render();
  43.             }
  44.  
  45.             // Reset stuff every second for the new "FPS" and "UPS"
  46.             if (System.currentTimeMillis() - lastTimer >= 1000) {
  47.                 lastTimer += 1000;
  48.                 FPS = frames;
  49.                 UPS = ticks;
  50.                 frames = 0;
  51.                 ticks = 0;
  52.             }
  53.         }
  54.         stop();
  55.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement