I am following a tutorial, and below is a startup method for generating logical and frame updates. I understand how ticks are updated at 60 ticks per second, but I don’t understand how we adjust the frame per second here.
Right now with Thread.sleep (2), the frame per second is about 460. Without it, the numbers go up, about 10 million updates per second. Does Thread.sleep (2) code pause a thread in just 2 milliseconds? Why / how does Thread.sleep work here to keep it to a minimum?
Isn’t it easier to create nsPerFrame = 1000000000D / (FPS) D to install any FPS I want, as it did with ticks?
public void run(){
long lastTime = System.nanoTime();
double nsPerTick = 1000000000D / 60D;
int frames = 0;
int ticks = 0;
long lastTimer = System.currentTimeMillis();
double delta = 0;
while(running){
long now = System.nanoTime();
delta += (now - lastTime) / nsPerTick;
lastTime = now;
while(delta >= 1){
ticks++;
tick();
delta-= 1;
}
try{
Thread.sleep(2);
} catch(InterruptedException e){
e.printStackTrace();
}
frames++;
render();
if(System.currentTimeMillis() - lastTimer >= 1000){
lastTimer += 1000;
System.out.println(ticks + "," + frames);
frames = 0;
ticks = 0;
}
}
}
source
share