Skip to main content
2 of 2
edited tags

Passing elapsed time to the update function from the game loop

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.