Frage

i'm having a tremendous difficulty understanding a piece of code that controls a loop of a game... I can't understand the purpose of this while loop "while(unprocessedSeconds > secondsForEachTick)" and why the FPS counter if inside of that if(tickCounter % 60 ==0) like follows on code:

public void run() 
{
    int frames = 0;
    double unprocessedSeconds = 0;
    long previousTime = System.nanoTime();

    double secondsForEachTick = 1/60.0; 


    int tickCount = 0; //RENDER COUNTER
    boolean ticked = false;

    while (running) 
    {
        long currentTime = System.nanoTime();
        long passedTime = currentTime - previousTime;

        previousTime = currentTime;

        unprocessedSeconds = unprocessedSeconds + passedTime / 1000000000.0;

        int count = 0;
        while(unprocessedSeconds > secondsForEachTick)
        {   
            tick();
            count++;
            unprocessedSeconds -= secondsForEachTick; 

            ticked = true;
            tickCount++;

            if(tickCount % 60 == 0){
                System.out.println(frames + " fps");
                previousTime += 1000;
                frames = 0;
            }
        }
        System.out.println("Iterações do loop: "+count);

        if(ticked)
        {
            render();
            frames++;
            ticked = false;
        }

    }
}
War es hilfreich?

Lösung

That inner while cycle ensures that the game update is based on fixed time, rather than frame time. The unprocessed time is getting collected and as soon as it is greater than the time frame for one tick, it calles tick().

The TickCount is basically counts the ticks (the tick time is 1/60 sec, so 60 tick/sec), and as soon as it 1 sec elapsed it prints the collected frames (so FPS). Also, ticked signals that something may changed in the game, so a new render is required.

Andere Tipps

This loop is used to have constant time in game. So if for some reason you get lag, you will do several logic update and one render. I assume tick() performs some logic operations.

To be more precise. For example, you have bullet, and bullet position need to be updated at 0.1s to do proper collision test. If for some reason delta time grows to 0.4s your bullet will fly through walls. To deal with it you performs several iterations with smaller time step, this loop doing it.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top