I have a simple question. It’s about basic game loop. When I’ve written my apps, I used a loop like this:
while (true)
{
int delta = (int) (System.currentTimeMillis() - lastLoopTime);
logic(delta);
lastLoopTime = System.currentTimeMillis();
draw((Graphics2D) strategy.getDrawGraphics());
strategy.show();
// Calculate sleep time
try { Thread.sleep (sleepTime);}catch(Exception e) {}
}
recently i started looking at others’ people sources and I’ve found loops like this:
(source taken from http://www.cokeandcode.com/games/4k/city4k/R.java)
while (true)
{
int delta = (int) (System.currentTimeMillis() - lastLoopTime);
for (int i=0;i<delta/10;i++) {
logic(10);
}
logic(delta % 10);
lastLoopTime = System.currentTimeMillis();
draw((Graphics2D) strategy.getDrawGraphics());
strategy.show();
}
Could you please explain me the reason, why is it better to break logic into 10 millisecond calls plus one delta % 10 call?
Second point is: code below never sleeps. I thought it is good idea to call Thread.sleep from a game loop to give some time to other threads. Actually this code is from 4k contest so this might be the reason.
In other pieces of code I’ve seen Thread.yield() instead of Thread.sleep(). Which approach is preferable?


