I made my first game in Java - Snake, it's main loop looks like this
while (true)
{
long start = System.nanoTime();
model.eUpdate();
if (model.hasElapsedCycle())
{
model.updateGame();
}
view.refresh();
long delta = (System.nanoTime() - start) / 1000000L;
if (delta < model.getFrameTime())
{
try
{
Thread.sleep(model.getFrameTime() - delta);
} catch (Exception e)
{
e.printStackTrace();
}
}
}
But in my project's requirments there is a responsivity point, so I need to change the Thread.sleep()
into something else, but I have no idea how to do this in an easy way.
Thanks in advance for any advice.
I've done a simple game or two with Java and to handle the main game loop I've used a Swing Timer
. The timer will allow you to set an ActionListener
to be fired after a provided delay
has elapsed. The in-between delay would be derived from your frame rate. The most basic usage would look like:
Timer timer = new Timer(delay, listener);
timer.start();
This would set the initial and in-between delays to the same value. You could also set them to be different values if needed like so:
Timer timer = new Timer(delay, listener);
timer.setInitialDelay(0);
timer.start();
In the above example, the listener
will fire ASAP after starting and with a delay
in-between thereafter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With