Simple rendering produces minor stutter

Posted by Ben on Game Development See other posts from Game Development or by Ben
Published on 2014-06-18T21:29:36Z Indexed on 2014/08/18 16:48 UTC
Read the original article Hit count: 248

Filed under:

For some reason, this game loop renders the movement of a simple rectangle with no stuttering.

    double currTime;
    double prevTime = System.nanoTime() / NANO_TO_SEC;
    double FPSTIMER = System.nanoTime();
    double maxTimeDiff = 100.0 / 1000.0;
    double delta = 1.0 / 60.0;
    int processes = 0, frames = 0;

    while(true){
        currTime = System.nanoTime() / NANO_TO_SEC;
        if(currTime - prevTime > maxTimeDiff) prevTime = currTime;
        if(currTime >= prevTime){
            process();
            processes++;
            prevTime += delta;
            if(currTime < prevTime){
                render();
                frames++;
            } 
        }
        else{
            try{
                Thread.sleep((long) (1000 * (prevTime - currTime)));
            }
            catch(Exception e){}
        }

        if(System.nanoTime() - FPSTIMER > 1000000000.0){
            System.out.println("Process: " + (1000 / processes) + "ms FPS: " + (1000 / frames) + "ms");
            processes = frames = 0;
            FPSTIMER += 1000000000.0;
        }
    }

But for this game loop, I get really minor stuttering where the movement does not look smooth.

    long prevTime = System.currentTimeMillis();
    long prevRenderTime = 0;
    long currRenderTime = 0;
    long delta = 0;
    long msPerTick = 1000 / 60;
    int frames = 0;
    int ticks = 0;
    double FPSTIMER = System.currentTimeMillis();

    while (true){
        long currTime = System.currentTimeMillis();
        delta += (currTime - prevTime) / msPerTick;
        prevTime = currTime;

        while (delta >= 1){
            ticks++;
            process();
            delta -= 1;
        }

        prevRenderTime = System.currentTimeMillis();
        render();
        frames++;
        currRenderTime = System.currentTimeMillis();

        try{
            Thread.sleep((long) ((1000 / FPS) - (currRenderTime - prevRenderTime)));
        }
        catch(Exception e){}

        if(System.currentTimeMillis() - FPSTIMER > 1000.0){
            System.out.println("Process: " + (1000.0 / ticks) + "ms FPS: " + (1000.0 / frames) + "ms");
            ticks = frames = 0;
            FPSTIMER += 1000.0;
        }

Is there any critical difference that I'm missing here? The one thing I noticed is that if I uncap the fps for the second game loop, the stuttering goes away. It doesn't make sense to me. Also, the second game loop came from Notch's Minicraft code with just my thread sleeping code added in.

© Game Development or respective owner

Related posts about java