Search code examples
javaswingjpanelframe-rategame-loop

Java2D game stutters randomly. What am I doing wrong?


I am currently developing a 2D game using Swing components. Each time I run my game it stutters randomly at some points. This is my game loop code:

public class FixedTSGameLoop implements Runnable
{
    private MapPanel _gamePanel;

    public FixedTSGameLoop(MapPanel panel)
    {
        this._gamePanel = panel;
    }

    @Override
    public void run()
    {
        long lastTime = System.nanoTime(), now;
        double amountOfTicks = 60.0;
        double amountOfRenders = 120.0;
        double nsTick = 1000000000 / amountOfTicks;
        double nsRender = 1000000000 / amountOfRenders;
        double deltaTick = 0;
        double deltaRender = 0;
        while (this._gamePanel.isRunning())
        {
            now = System.nanoTime();
            deltaTick += (now - lastTime) / nsTick;
            deltaRender += (now - lastTime) / nsRender;
            lastTime = now;
            while (deltaTick >= 1)
            {
                tick();
                deltaTick--;
            }
            while (deltaRender >= 1)
            {
                render();
                deltaRender--;
            }
        }
    }

    private void tick()
    {
        /**
         * Logic goes here:
         */
        this._gamePanel.setLogic();
    }

    private void render()
    {
        /**
         * Rendering the map panel
         */
        this._gamePanel.repaint();
    }
}

I have tried multiple times to omit certain code parts, thinking that they cause lag, but I have found nothing that caused it particularly, so I think the problem lies within my game loop mechanism. Thank you for your help!


Solution

  • Your game loop must contain a "Thread.sleep" on order to sleep the amount of time needed to respect your target FPS.

    The main loop is supposed to contain 1 tick() and 1 render().

    Your current implementation is flooding the paint manager, slowdowns will appear when the underlying buffers will be full and when the garbage collector will do its job.