Currently trying to manage a game loop to a steady 60 frames. I followed the example I saw to a T, yet not getting expected output. Starting to wonder if my computer is just slow.
I use the following code to manage the number of renders per loop:
@Override
public void run() {
int fps = 60; //Number of renders wanted per second
double timePerTick = 1000000000/fps; //Alotted nanoseconds given desired fps
double delta = 0;
long now;
long lastTime = System.nanoTime();
int ticks = 0; //To track the number of times render() is called in 1 second
while(isRunning) {
now = System.nanoTime();
delta += (now - lastTime)/timePerTick; //Delta here is very small #. Represents amount of the timePerTick used after looping through one time.
timer += now - lastTime;
lastTime = now;
if(delta >= 1) {//This dictates whether a render occurs or not.
render();
ticks++;
delta = 0;
}
if(timer >= 1000000000) {//Prints out how many renders occurred in one second
System.out.println("FR at " + ticks);
ticks = 0;
timer = 0;
}
}
}
In the example I followed, this code generated 60 frames consistently per printout. Mine is consistently printing out 23, 24, 17, 20, etc. No matter how I changed the if(delta >= 1)
to something like if(delta >= .0000001)
, it still prints out around the same number of renders/frames per second.
Obviously with a lower threshold, more renders should happen... but that is not happening. So at this point, I am extremely confused. I know I could use Thread.sleep()
for this, but its not guaranteed to be accurate.
I'm not sure if y'all will want to see my render() method, but here it is:
private void render() {
strategy = myCanvas.getBufferStrategy();
if(strategy == null) {
myCanvas.createBufferStrategy(3);
return;
}
do {
do {
g = strategy.getDrawGraphics();
g.clearRect(0, 0, 1000, 1000);
BufferedImage myImage = ImageLoader.getImage(path);//Do this in an instantiation method
g.drawImage(myImage.getSubimage(0, 0, 110, 125), x, 0, 300, 300, null);
strategy.show();
x++;
}while(strategy.contentsRestored());
g.dispose();
}while(strategy.contentsLost());
}
Any help is greatly appreciated!