Hi y’all I see some strange things happening when I use the following code to create a game loop:
private static final int MAX_CPS = 50;
private static final int MS_PER_FRAME = 1000 / MAX_CPS;
public void run()
{
while (running)
{
long cycleStartTime = System.currentTimeMillis();
repaint();
if (System.currentTimeMillis() - lastCPSTime > 1000)
{
lastCPSTime = System.currentTimeMillis();
cps = cyclesThisSecond;
cyclesThisSecond = 0;
}
else
cyclesThisSecond++;
long timeSinceStart = (System.currentTimeMillis() - cycleStartTime);
if (timeSinceStart < MS_PER_FRAME)
{
try
{
Thread.sleep(MS_PER_FRAME - timeSinceStart);
}
catch (InterruptedException e) {}
}
}
}
As you can see, it’s just a regular gameloop. The variable cps is drawn to screen every second.
However when I set MAX_CPS=50, cps has the value of 32. When MAX_CPS=40, then cps is still 32! When MAX_CPS=30 then cps is 20. When MAX_CPS=65 then cps is 65! When MAX_CPS=100, then cps is still 65!
I can understand there’s some overhead in using the Thread.sleep statement, but this behaviour I cannot explanin.
Can somebody shine a light on this?
Thanx!
Ronnie