A game loop problem

I had been trying to make a game engine and got nothing but problems. Here are the problems.

  • Different speeds on each run
  • Highly slowed rendering
  • The game freezes after 5-10 min

And here’s my code.


/* Only run this in another thread */
public void gameLoop(){
    long UPS = 1000/30;
    long expectedTime = 1000/UPS;  // 30ms
    long elapsedTime = 0;
    while (running){
        long start = getCurrentTime(); // in ms
        if (elapsedTime<=expectedTime){
            updateGame(elapsedTime);
            displayGame();
        }
        long end = getCurrentTime();
        elapsedTime = end - start;
        long sleepTime = expectedTime - elapsedTime;
        if (sleepTime>0){
            try {
                Thread.sleep(sleepTime);
            } catch (Exception e){}
        }
    }
}

Could anyone shed some light please?

You could save yourself the headache and use the Sync class from LWJGL :slight_smile:

http://java-game-lib.svn.sourceforge.net/viewvc/java-game-lib/trunk/LWJGL/src/java/org/lwjgl/opengl/Sync.java?revision=3803&view=markup

But I’m not using LWJGL. I’m trying to make an engine which is independent of any other engine.

I’ll ask the standard question…is there any reason you are doing this rather than leveraging an existing engine? Are you building the engine as a learning experience? Do you think your engine has requirements that the pre-existing ones don’t have? You say you’ve had nothing but problems, if so, why not use what already exists if it’s getting in the way of making a game?

One thing you can do is use System.nanoTime() which is a more accurate clock (I believe, someone correct me if I am wrong). The rendering and game issue problem might not have anything to do with your game loop. The issue may be within your updateGame and displayGame methods.

I was creating the engine just for learning purposes. What I want to is make each frame take same amount of time (30 ms) unlike the tutorials on game loop at dewitters and JGO.

And here’s my method


public long getCurrentTime(){
    return (System.nanoTime()/1000000);
}

The Sync class from LWJGL is something you can pull out and use independently of LWJGL. It has no dependencies on any other part of LWJGL except for some really trivial time-related code from Sys that you can also copy out. Just throw in the requisite copyright statement and you’re set.

Uhh lwjgl is not really an engine so… If you want to make an engine (which is what I am trying to do) that has any sort of performance outside of tetris like games, you really need opengl.

Is this the same as Display.sync?

Yes.

This is not the way to do digital timers.

That isn’t exactly helpful, eh? “You’re doing it wrong!” :point:

I’m too lazy to redo a write-up and hoping to prompt someone else to. :slight_smile:

OK: Here’s a mini-write up: http://www.java-gaming.org/topics/jvm-reports-timer-taking-longer-than-it-should/24117/msg/202078/view.html#msg202078