views:

414

answers:

2

I've done a series of questions about J2ME Game developing, and in a recent one, Neil Coffey commented

As a side issue-- do you REALLY want to do 100 ticks/second in a J2ME game? As I think sb has mentioned, you should really also sleep to the next desired wake-up point, not a fixed duration each time.

For some reason, that thing stuck in my mind and now I want the answers, what do I need to make my gameloop sleep to the desired wake-up point, I don't really know where is that point xD (theoretically speaking).

For the sake of feedback, this is a simplified version of my gameloop:

public void run() {
    Graphics g = this.getGraphics();
    while (running) {
        long diff = System.currentTimeMillis() - lastLoop;
        lastLoop = System.currentTimeMillis();
        input();
        this.level.doLogic();
        render(g, diff);
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            stop(e);
        }
    }
}

Thanks for your help!!

A: 

If you decide that you want to render every 10 milliseconds, then you:

loop {
  - record current time; render
  - do input/logic
  - check the current time, and calculate elapsed time
    - if less than 10 ms has elapsed, calculate the remaining time (10 millis - elapsed time); sleep for this duration
}

I understand that there may be issues with timer resolution (for example, Thread.sleep(10) may not sleep for exactly 10 ms; and System.currentTimeMillis() may not return results with granularity down to 1 ms). This is platform dependent.

JimN
+2  A: 

There is an excellent article on game loops here, if you haven't read it already.

From my experience writing J2ME games, you'll want to minimize how much you do anything in a game loop, as a poorly written game loop can quickly drain a phones puny battery. That is, if you're rendering ever 10 milliseconds, make sure to check to see if anything has changed, and if not, skip it.

cdmckay