Matthew Bland
Posted on February 4, 2020
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
}
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;
}
}
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();
And finally, the if statement:
if (System.currentTimeMillis() - lastTick >= (1000 / 60)) {
lastTick = System.currentTimeMillis();
//tick and stuff
}
Hope this helps!
π πͺ π
π©
Matthew Bland
Posted on February 4, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.