Java Main Game Loop

Eventually you’ll want to move to something like LWJGL, but let me stress, keep doing what you’re doing here for now. It will teach you fundamentals.

Good job on your loop. Looks nice, let me offer a few pointers:

  • Repaint will not render the screen immediately. It tells the RepaintManager to render when its ready. Use invalidate paintImmediately instead. paintImmediately will block execution until the component has been redrawn so you can measure rendering time.
  • Thread.sleep typically has a few milliseconds drift. You should be using it to keep your loop from using too much CPU, but make sure you understand if you sleep 10 milliseconds you might sleep 5 milliseconds or you might sleep 20.
  • Lastly: double delta = updateLength / ((double)OPTIMAL_TIME); If updateLength is less than OPTIMAL_TIME, don’t call update. In other words, if delta is less than one, don’t update. This tutorial explains why better than I ever could.

Leave a Comment