Hey. I am currently developing a 2D Java game using Swing components.
The game randomly stutters. Sometimes it runs completely smooth for the first minute and then it randomly jitters like mad, sometimes it starts of as a jittery mess.
Iv’e tried to omit certain parts of my code, thinking that they cause the lag, and now I am 100% sure that the problem lies within the way my game loop is written. Here it is:
package map;
public class GameLoop implements Runnable
{
private Thread _gameThread;
private MapPanel _gamePanel;
private final double _updateCap = 1.0 / 60.0;
private int _fps;
public GameLoop(MapPanel panel)
{
this._gamePanel = panel;
}
public void startGame()
{
this._gameThread = new Thread(this);
this._gameThread.start();
}
@Override
public void run()
{
double firstTime = 0,
lastTime = System.nanoTime() / 1000000000.0,
passedTime = 0,
unprocessedTime = 0,
frameTime = 0;
int frames = 0;
while (this._gamePanel.isRunning())
{
firstTime = System.nanoTime() / 1000000000.0;
passedTime = firstTime - lastTime;
lastTime = firstTime;
unprocessedTime += passedTime;
frameTime += passedTime;
while (unprocessedTime >= _updateCap)
{
unprocessedTime -= _updateCap;
this.tick();
if (frameTime >= 1.0)
{
frameTime = 0;
_fps = frames;
frames = 0;
System.out.println("FPS: " + _fps);
}
}
render();
frames++;
/**
* Preventing over-consumption of the CPU -
*/
try
{
Thread.sleep(1);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void render()
{
_gamePanel.repaint();
}
private void tick()
{
_gamePanel.setLogic();
}
}
When am I doing wrong? What alternatives can you recommend if I want a game loop that can ensure a relatively smooth gameplay without dealing with anything that is way too advanced?
Thanks alot!