I had an old pure Java 2D top-down game that I'm trying to reformat a bit. Before, I had a bit of a messy game loop that didn't use delta timing for any movements or animations. Now, I'm trying to implement this delta timing.
I implemented delta timing into the game loop with two framerates (60FPS and 30FPS) to test it, but I noticed that the movement created with the 30FPS was half of what was obtained using the 60FPS.
When I moved the player, I did something like:
posX += Game.deltaTime * SPEED;
and this didn't work well because the delta time was the same for both the 30FPS and 60FPS.
So, I did some calculations... I run into some problems if I use change the player's position from the update() method, because it runs at a constant 60UPS.
Here are my calculations
int deltaXPerSecond = Game.deltaTime() * SPEED * 60;
// To get the delta X over a second, I multiplied deltaX by 60 (UPS)
// with 30FPS, it was 9.9, with 200FPS it was 1.5
// Game Loop
private static final double UPDATES_PER_SECOND = 1.0 / 60.0;
@Override
public void run() {
/*
* Note: This game loop uses Majoolwip's game loop.
* https://www.youtube.com/watch?v=4iPEjFUZNsw&list=PL7dwpoQd3a8j6C9p5LqHzYFSkii6iWPZF
*/
double firstTime = 0;
// converts to seconds because System.nanoTime is extremely accurate.
double lastTime = System.nanoTime() / 1000000000.0;
double passedTime = 0;
double unprocessedTime = 0;
double frameTime = 0;
int frames = 0;
int fps = 0;
boolean render = false;
// Continuously repeats this loop until the game is stopped.
while (running) {
render = false;
firstTime = System.nanoTime() / 1000000000.0; // converts to seconds.
// Gets how many milliseconds have passed between now and the last time.
passedTime = firstTime - lastTime;
deltaTime = (float) passedTime;
lastTime = firstTime;
unprocessedTime += passedTime;
frameTime += passedTime;
while (unprocessedTime >= UPDATES_PER_SECOND) {
unprocessedTime -= UPDATES_PER_SECOND;
// Sets render to true. This makes the game render only when it updates
render = true;
// Updates the game
if (frameTime >= 1.0) {
frameTime = 0;
fps = frames;
frames = 0;
System.out.println("FPS: " + fps);
}
update();
}
if (render) {
frames++;
render();
}
else {
/*
* If the game doesn't need to render or update,
* the GameLoop thread sleeps for 1 millisecond,
* causing a decrease in CPU usage.
*/
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
What am I doing wrong? Shouldn't these numbers be approximately the same regardless of the frame rate? Do I need to change the game loop? Please let me know what I am missing.