public
anonymous / loop.java
Created

Game Loop Attempt

  • Download Gist
loop.java
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
public void runGame(){
Graphics2D gImage = (Graphics2D)canvas.getGraphics();
long lastUpdate = System.nanoTime();
long startTime = System.nanoTime();
long endTime = System.nanoTime();
int counter = 0;
//UPS = updates per second
int UPS = 1000000000 / 25;
while(isRunning){
//run update at 25 updates per second
while(System.nanoTime() - lastUpdate > UPS){
updateGame();
lastUpdate += UPS;
}
endTime = System.nanoTime();
 
//Code to see if the update method is really running at 25 updates per second
if(endTime - startTime >= 1000000000){
System.out.println(counter);
counter = 0;
startTime = System.nanoTime();
}
 
//Calculate how much to move entities based on the time between updates
float interpolation = (float)(System.nanoTime() - lastUpdate) / (float)UPS;
puck.interpolate(interpolation);
p1.interpolate(interpolation);
p2.interpolate(interpolation);
checkCollisions();
//render without an upper limit
render(gImage, interpolation);
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.