This is just one way to do it(it's very long but VERY precise - I recommend it for game development). In this case I'm using the run()
method from the Runnable interface to execute the code.
public void run(){
long lastTime = System.nanoTime();
final double ns = 1000000000.0 / 60.0;
double delta = 0;
while(true){
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
while(delta >= 1){
the code you want to be executed
delta--;
}
}
}
Explanation Line by Line:
Basically, I store the current time in nanoseconds in lastTime
. Then in ns
I store 1/60th of a second in nanoseconds and create a variable delta
.
After this, I go inside the infinite while loop(it doesn't have to be infinite) and store the current time in nanoseconds once again in now
. This is to take into account the amount of time that took the computer to go from the lastTime
declaration line to the while loop line.
After doing all this, I add to delta
the difference of now
and lastTime
divided by the 1/60th of a second(ns
) I mentioned. This means that every time delta
is equal to 1, 1/60th of a second will have passed.
Right after this, I make lastTime
be the same as now
. In the while loop that comes afterwards I check if delta is equal or greater than 1 and then in there you should put all the code you want to be executed 60 times per second. Don't forget to substract 1 from delta
so it doesn't loop endlessly.
Analyze the code thoroughly and see if you can understand it. If you can't, I'll clarify further. I insist that this is just one possible way to do it, but there are many more ways.
Note: In some cases, you will never even need delta
, but it is very helpful for some purposes.
Credit for the code: Most of this code(at least where I got it & learned it) is extracted from TheCherno's Game Programming Series
Have a great day!