Hey all,
I’m trying to make a frame loop which can be limited. The code I have written is intended to limit it to 60 frames per second. However, I only get 40 frames per second. When I remove my limiter code, I get more than 250 frames per second (and if I remove the random balls on the screen, I get over 800 FPS, without the limiter code). I’m hoping somebody here can shed some light on what I’m doing wrong or what I need to do.
Here’s my code:
import java.awt.*;
import java.awt.image.*;
public class FPS extends Canvas implements Runnable {
private int FPS = 60;
private int gameW = 1024;
private int gameH = 768;
private Graphics screen;
private BufferedImage buffer;
private int fps = 0;
private int frames = 0;
private long lastLoopTime = System.currentTimeMillis();
public FPS() {
setSize(gameW, gameH);
}
public void addNotify() {
super.addNotify();
buffer = new BufferedImage(gameW, gameH, Transparency.OPAQUE);
screen = buffer.getGraphics();
(new Thread(this)).start();
}
public void run() {
long next = System.currentTimeMillis()+(1000/FPS);
while(true) {
if (System.currentTimeMillis() >= next) {
long last = (System.currentTimeMillis()-lastLoopTime);
if (last >= 1000) {
fps = frames;
frames = 0;
lastLoopTime = System.currentTimeMillis();
}
frames++;
screen.setColor(Color.black);
screen.fillRect(0, 0, gameW, gameH);
gameLoop();
next = System.currentTimeMillis()+(1000/FPS);
}
Graphics g = getGraphics();
g.drawImage(buffer, 0, 0, this);
g.dispose();
}
}
public void gameLoop() {
screen.setColor(Color.green);
screen.drawString("FPS = "+fps, 100, 100);
int w = 20;
int h = 20;
screen.setColor(Color.gray);
for (int i=0; i<100; i++) {
int x = (int)(Math.random() * (gameW-w));
int y = (int)(Math.random() * (gameH-h));
screen.drawOval(x, y, w, h);
}
}
public static void main(String args[]) {
Frame f = new Frame("FPS");
f.add(new FPS());
f.setResizable(false);
f.pack();
f.show();
}
}
System specs are as follows:
CPU: 2GHz AMD Athlon 64-bit 3200+
RAM: 1GB DDR2 SDRAM
Video: 256MB nVidia GeForce 7600GT
Thanks in advanced,
Jamison