I am making a 2D platform in Java, and I’m using a Swing timer, it is set at 5 milliseconds interval. However, sometimes it is smooth movement at a good speed, but then randomly it will become super fast and sometimes super slow. What could be the reason for this?
Code:
public Board() {
addKeyListener(new KeyListener());
setFocusable(true);
setBackground(new Color(204,250,255));
//draws the object off the screen in memory, then brings it in
setDoubleBuffered(true);
...(other code not relevant)...
timer = new Timer(5, this);
timer.start();
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
//draw platform
for(int i = 0; i < platform.length; i++) {
//g2d.setColor(new Color(0,0,0));
//g2d.drawRect(platform[i].getX(), platform[i].getY(), platform[i].getWidth(), platform[i].getHeight());
g2d.drawImage(platform[i].getImage(), platform[i].getX(), platform[i].getY(), this);
}
//draw guy
g2d.drawImage(guy.getImage(), guy.getX(), guy.getY(), this);
//destroy unneeded process
Toolkit.getDefaultToolkit().sync();
g.dispose();
}
Basically, the cycle function decides whether the character needs to move or not, and moves it if it does.
It is hard to make Java work as a real-time systems…. because of unknown factors like when the OS will schedule your process to run and GC. Since you are trying to update the game at 200 fps (if my math is correct) you might want to try the following approach. To make the game smoother I would try to find the time between the current event fired and the last event fired, now theoretically that might be 5ms but sometimes it will be 7ms (going super slow) and sometimes it will be 3ms (going super fast). Ones you have the time between the two event I would calculate where the animation should be, so if the time is 3ms then the animation will be a bit before the 5ms time. Lets take a simple example where your are trying to update the X position of a image 5 px every 5ms.