Simple Animation Loop in Java

If you want to show some animation, maybe for a simple java game, then you need to render a certain amount of frames per second. For a smooth animation you want 30 to 60 frames per second. But sometimes the needed calculations need a bit longer so the delay until the drawing of the next frame needs to be shorter. For this an animation loop is needed. I have implemented a very simple animation loop for Java 8+ that can be paused and started.

It’s a single file on GitHub:
https://gist.github.com/claudemartin/d2a3e3c0f3ecbc10d695

The animation loop is thread-safe, but you need to make sure all data needed to render one frame is thread-safe too. The callback action has one argument. That is the time stamp of the frame that needs to be rendered. The parameter is the amount of nanoseconds passed since the first start of the animation, without the time of the pauses. For linear animations this can be used to calculate the current position of moving objects.

Leave a Reply

Your email address will not be published. Required fields are marked *