I have noticed that my little car game run at 90fps if I have spotify on. 90fps might sounds good but game is limited to 60fps and this can cause some problems.
Here’s some of the code (it’s not all that I tryed, have to test the 1ms sleep)
public void setupStrategy(){
createBufferStrategy(2);
bufstrategy = getBufferStrategy();
}
public void runAnimation(){
//note: I was experimenting with separate thread, doesn't change anything..
startNanos = System.nanoTime();
//change timer resolution
Thread thread = new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(Long.MAX_VALUE);
} catch (Exception e) { }
}
});
thread.setDaemon(true);
thread.start();
Thread t = new Thread(new Runnable(){
public void run(){
while(true){
gameLoopBody();
}
}
});
t.start();
}
public void gameLoopBody() {
long frameStart = System.nanoTime();
boolean needwait = true;
//update state (just simple..)
x += 3*dir;
if (x > 800){
dir=-1;
} else
if (x<5){
dir=1;
}
//show
do {
do {
Graphics2D gg = (Graphics2D) bufstrategy.getDrawGraphics();
Point mousePos = getMousePosition();
gg.fillRect(0, 0, getWidth(), getHeight()); //clear bg
//note: images are some random PNGs from net with transparency
//(I originaly wanted to test the performance of that)
if(mousePos!=null)
gg.drawImage(bgi,mousePos.x,mousePos.y, null);
gg.drawImage(luigi,x,40,80,80,null);
gg.drawImage(luigi,50,40,200,200,null);
gg.drawImage(luigi,90,80,100,100,null);
gg.drawImage(luigi,20,90,200,200,null);
gg.drawImage(luigi,40,200,100,100,null);
if( mousePos!=null )
gg.drawImage(luigi,mousePos.x,mousePos.y,50,50,null);
gg.setColor(Color.WHITE);
gg.drawString("FPS: "+String.format("%1$010.2f",this.fps),10,10);
gg.dispose();
} while (bufstrategy.contentsRestored());
//schedule swap
if( needwait ){
int timing=1;
//account there state changes and drawing
long timeout = (int)((1000.0/60.0)*1000000)-(System.nanoTime()-frameStart);
// long timeout = (int)((1000.0/60.0)*1000000);
if(timing==1){
if(timeout>0)
LockSupport.parkNanos(timeout);
}
//note: this is nearly perfect, i don't account anything to the timeout
if(timing==2){
long st = System.nanoTime();
while( (int)(1000.0/60.0)*1000000-(System.nanoTime()-st) > 0 )
Thread.yield();
}
lastTime = System.nanoTime();
needwait=false;
}
bufstrategy.show();
} while (bufstrategy.contentsLost());
frames++;
long currTime = System.nanoTime();
fps = ((long)1.0/((currTime-frameStart)/1e9));
}
I also found, that the performance is good only with opengl pipeline. This is intel gma4500m.