DEV Community

Matthew Bland
Matthew Bland

Posted on

Writing Good Tick Limiters

Something I've seen in sooo many game tutorials at the start is that a lot of people are making a tick limiter much more difficult than it really should be. If you're not familiar with it, a tick limiter is used to limit the number of ticks per second so that the game runs the same speed on every device.

(All code is written in Java).

I see so many people do this:

long newTime = System.nanoTime(); long frameTime = newTime - currentTime; currentTime = newTime; accumulator += frameTime; while (accumulator >= nanosPerLogicTick) { //tick and stuff } 
Enter fullscreen mode Exit fullscreen mode

Or the even worse one:

int fps = 60; double timePerTick = 1000000000 / fps; double delta = 0; long now; long lastTime = System.nanoTime(); long timer = 0; int ticks = 0; while(running){ now = System.nanoTime(); delta += (now - lastTime) / timePerTick; timer += now - lastTime; lastTime = now; if(delta >= 1){ //tick and stuff ticks++; delta--; } if(timer >= 1000000000){ ticks = 0; timer = 0; } } 
Enter fullscreen mode Exit fullscreen mode

Wow... doesn't that seem a little extra? Turns out in Java it's as simple as this:

(Global var containing last time)

private long lastTick = System.currentTimeMillis(); 
Enter fullscreen mode Exit fullscreen mode

And finally, the if statement:

if (System.currentTimeMillis() - lastTick >= (1000 / 60)) { lastTick = System.currentTimeMillis(); //tick and stuff } 
Enter fullscreen mode Exit fullscreen mode

Hope this helps!

Top comments (0)