Thought I’d share the code for my smooth scrolling game loop:
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.image.BufferStrategy;
import java.awt.event.KeyListener;
/**
* Main.java - A smooth scrolling game loop.
*
* @author Mario Gianota
*/
public class Main implements KeyListener {
/*
* Colour palette
*/
private static Color[] COLORS = new Color[] {
Color.red, Color.blue, Color.green, Color.white, Color.black,
Color.yellow, Color.gray, Color.cyan, Color.pink, Color.lightGray,
Color.magenta, Color.orange, Color.darkGray };
Frame mainFrame;
long lastTime;
int fps;
int frameCounter;
long elapsedTime;
long delayTime = 0;
Rectangle rect;
public Main(GraphicsDevice device) {
try {
// Setup the frame
GraphicsConfiguration gc = device.getDefaultConfiguration();
mainFrame = new Frame(gc);
mainFrame.setUndecorated(true);
mainFrame.setIgnoreRepaint(true);
mainFrame.setVisible(true);
mainFrame.setSize(640, 480);
mainFrame.setLocationRelativeTo(null);
mainFrame.createBufferStrategy(3);
mainFrame.addKeyListener(this);
// Cache the buffer strategy and create a rectangle to move
BufferStrategy bufferStrategy = mainFrame.getBufferStrategy();
rect = new Rectangle(0, 100, 50, 50);
// Main loop
while(true) {
long time = System.nanoTime();
calculateFramesPerSecond();
// Update rectangle co'ords
rect.x+=4;
if( rect.x > mainFrame.getWidth() )
rect.x = -rect.width;
// Draw
Graphics g = bufferStrategy.getDrawGraphics();
drawScreen(g);
g.dispose();
// Flip the buffer
if( ! bufferStrategy.contentsLost() )
bufferStrategy.show();
// Delay for a period of time equal to 1/60th of a
// second minus the elapsed time
elapsedTime = System.nanoTime() - time;
delayTime = 1000000000L/60 - elapsedTime;
time = System.nanoTime();
while( System.nanoTime() - time <= delayTime)
;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
device.setFullScreenWindow(null);
}
}
private void drawScreen(Graphics g) {
g.setColor(COLORS[1]);
g.fillRect(0, 0, 640, 480);
g.setColor(COLORS[3]);
g.drawString("FPS: "+ fps, 0, 17);
g.setColor(COLORS[0]);
g.fillRect(rect.x, rect.y, rect.width, rect.height);
}
private void calculateFramesPerSecond() {
long time = System.nanoTime();
if( time - lastTime >= 1000000000L ) {
fps = frameCounter;
lastTime = time;
frameCounter = 0;
}
frameCounter++;
}
public void keyPressed(KeyEvent e) {
if( e.getKeyCode() == KeyEvent.VK_ESCAPE ) {
System.exit(0);
}
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
public static void main(String[] args) {
try {
GraphicsEnvironment env = GraphicsEnvironment.
getLocalGraphicsEnvironment();
GraphicsDevice device = env.getDefaultScreenDevice();
Main test = new Main(device);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Have fun.
–Mario