I am making a game, and the requirement is to make it have at least 30FPS and shouldn't drop below. Would what I have below achieve this? Or am I off somewhere? Much help would be appreciated.
private long period = 6 * 1000000;
private static final int DELAYS_BEFORE_YIELD = 5;
long before, after, difference, sleep, oversleep = 0;
int delays = 0;
while (running)
{
before = System.nanoTime();
after = System.nanoTime();
difference = after - before;
if (sleep < period && sleep > 0)
{
try
{
Thread.sleep(sleep / 35000L);
oversleep = 0;
}
catch (InterruptedException e)
{
}
}
else if (difference > period)
{
oversleep = difference - period;
}
else if (++delays >= DELAYS_BEFORE_YIELD)
{
Thread.yield();
oversleep = 0;
delays = 0;
}
else
{
oversleep = 0;
}
}
You can set an upper bound to frame rate but not a lower bound that is guaranteed to be always followed.
You can make a function be called no more than 30 times per second but you can't be sure it will be called at least 30 times per second. At 30 fps you have 0.03s of time that will be distributed between your threads and usually the drawing one is the heaviest between them all (unless you have complex operations like AI or whatever but that should be solved by lowering their rate or precomputing what can be precomputed).
If time of draw + time of logic > 0.03
then there is no way to make your game run at least at 30fps.