JDJ Article on basics of game development

Chet Haase and I wrote an article in Java Development Journal on the basics of game development, following our JavaOne presentation this year.

The article:
http://www.sys-con.com/story/?storyid=46663&DE=1

The code for the demo:
http://ping.dev.java.net/

It’s nothing fancy, just the basics, but it could help those just staring writing games in java…

Why do you call both Thread.yield() and Thread.sleep(1) in your sync routine? Isn’t that redundant?

Yes it is redundant.

I was pretty sure it was. I think Thread.yeild() is the same as Thread.sleep(0) anyway… so I usually just have a delay value calculated that might come out as 0, and so it at least comes out equivalent to a yield if it can’t keep up at all and is basically busy-looping.

Thread.sleep is iirc only accurate down to 5msec. There may be platforms with higher accuracy, but I wouldn’t rely on that.

Here’s the code of my sync2 method. sync2b is the same, but it uses sleep if there are more than 5msec to waste. Both should be called with hz+1 as parameter.


public static void sync2(long fps)
{
      long gapTo = Sys.getTimerResolution() / fps + timeThen;
      timeNow = Sys.getTime();

      while(gapTo > timeNow+timeLate)
      {
            Thread.yield();
            timeNow = Sys.getTime();
      }

      if(gapTo<timeNow)
            timeLate = timeNow-gapTo;
      else
            timeLate = 0;

      timeThen = timeNow;
}

public static void sync2b(long fps)
{
      long gapTo = Sys.getTimerResolution() / fps + timeThen;
      timeNow = Sys.getTime();

      while(gapTo > timeNow+timeLate)
      {
            if(gapTo > timeNow+timeLate+5000L)
                  Thread.sleep(5);
            else
                  Thread.yield();
            timeNow = Sys.getTime();
      }

      if(gapTo<timeNow)
            timeLate = timeNow-gapTo;
      else
            timeLate = 0;

      timeThen = timeNow;
}

Yes, it is redundant now. Previously we had sleep(0) w/o the yield, and depending on platform it would sometimes throttle the cpu, so I added a yield. But then Chet did some research on the accuracy of sleep(0) on different platforms and found that it’s better to use sleep(1). And I never removed the redundant yield.

Note that we do want to have at least one yield there, in case our frames take longer that than we expected, so we at least give a chance to other threads.