Passing elapsed time to the update function from the game loop

Posted by Sri Harsha Chilakapati on Game Development See other posts from Game Development or by Sri Harsha Chilakapati
Published on 2012-11-02T06:50:03Z Indexed on 2012/11/02 11:19 UTC
Read the original article Hit count: 531

Filed under:
|

I want to pass the time elapsed to the update() method as this would make easy to implement the animations and time related concepts.

Here's my game-loop.

public void gameLoop(){
    boolean running = true;

    long gameTime = getCurrentTime();

    long elapsedTime = 0;
    long lastUpdateTime = 0;

    int loops;

    while (running){

        loops = 0;

        while(getCurrentTime()>gameTime && loops<Global.MAX_FRAMESKIP){
            elapsedTime = getCurrentTime() - lastUpdateTime;
            lastUpdateTime = getCurrentTime();

            update(elapsedTime);

            gameTime += SKIP_STEPS;
            loops++;
        }

        displayGame();
    }
}

getCurrentTime() method

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

update() method

long time = 0;

public void update(long elapsedTime){
    time += elapsedTime;
    if (time>=1000){
        System.out.println("A second elapsed");
        time -= 1000;
    }
}

But this is printing the message for 3 seconds.

Thanks.

© Game Development or respective owner

Related posts about game-loop

Related posts about timing