I am currently developing a game in Java and I ran into a problem
At first, I thought my game loop was working well as it was giving a similar amount of FPS as the tutorial I was following
Then I reach to the phase where I started implementing input from the user. When the user entered in the W key the sprite would move very rapidly to the bottom of the screen and then back up to the top for no explained reason
I think it is something to do with my game loop. As I did my research I deduced that my game loop is running way to fast. The only problem is that I haven't been able to slow down the loop. Or maybe it is a totally different problem
Can anyone please help
Run method of my game:
public void run() {
long lastTime = System.nanoTime();
double amountOfTicks = 60.0;
double ns = 1000000000 / amountOfTicks;
double delta = 0;
long timer = System.currentTimeMillis();
int frames = 0 ;
/* Game loop use:
* From timer calls to while loops to recursive function calls to keep the game alive
* Until a certain condition is meet (The loop)
*
* A way to delay the length of each loop iteration so you get a stable frame rate (The timing mechanism)
*
* A way to make the game speed remain independent of the speed of the loop (The interpolation)*/
//This is a variable timestep loop
while (running) {
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
while (delta >= 1) {
tick();
delta--;
}
if(running)
render();
frames++;
if(System.currentTimeMillis() - timer > 1000) {
timer += 1000;
System.out.println("FPS: " + frames);
frames = 0;
//While times updated per second is greater than one (allowing updates to be seen) call tick method of Handler class
/* Fixed timestep loops vs Variable timestep loops:
*
* Variable timestep loops: Great because the game will seem consistent regardless of how fast the players's computer is
* Allowing it to work on a variety of machines and update the game logic with very high attention to details happening in the game
* Graphics latency is not a problem as things are drawn as they change
*
*
*
* Fixed timestep loops: You know that every single timestep
* will take up the exact same length of time. Allows for consistent gameplay
* regardless of how fast a machine is as you know the tick rate of your machine
* Works wonderfully for math-heavy games with physics operations. Also good for networked games as packets are going and coming at a generally constant speed.
* Keeps game logic running at a very low rate while the frame rate can still and frame rate really high
* */
}
stop();
}
}
'''
Thanks!!!