0

I am currently working on a Java 2D based game, and this is my current tutorial-based game loop:

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 ns = 1000000000 / amountOfTicks;
    double delta = 0;
    long timer = System.currentTimeMillis();
    int updates = 0;
    int frames = 0;
    while (this._gamePanel.isRunning())
    {
        now = System.nanoTime();
        delta += (now - lastTime) / ns;
        lastTime = now;
        while (delta >= 1)
        {
            tick();
            updates++;
            delta--;
        }
        render();
        frames++;
        if (System.currentTimeMillis() - timer > 1000)
        {
            timer += 1000;
            System.out.println("FPS: " + frames + " TICKS: " + updates);
            frames = 0;
            updates = 0;
        }
    }
}

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

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

Now, I want to set a certain cap to the framerate. How do I do that in the most efficient way? *Any other general tips concerning the game loop itself will be highly appreciated! Thank you!

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Ido Sofi
  • 5
  • 3

1 Answers1

0

This is how I set up my game loop. You can change frameCap to any amount you would like.

    int frameCap = 120;
    int fps = 0;

    double delta = 0D;
    long last = System.nanoTime();
    long timer = 0L;

    while (true) {
        long now = System.nanoTime();
        long since = now - last;

        delta += since / (1000000000D / frameCap);
        timer += since;
        last = now;

        if (delta >= 1D) {
            tick();
            render();

            fps++;

            delta = 0D;
        }

        if (timer >= 1000000000L) {
            System.out.println("fps: " + fps);

            fps = 0;

            timer = 0L;
        }
    }
camo5hark
  • 214
  • 1
  • 5
  • You have to insert a "sleep" in your loop after render() in order to respect the 60fps limit. – BluEOS Jan 24 '18 at 11:36
  • Thank you for your answer camo5hark! BluEOS's comment was actually the tiny tip I needed to stop the rendering rate from going crazy high. – Ido Sofi Jan 24 '18 at 17:04