I am making a Java game and I want my game to run the same on any FPS so I'm using time delta between each update. This is the update method of the Player:
public void update(long timeDelta) { //speed is the movement speed of a player on X axis //timeDelta is expressed in nano seconds so I'm dividing it with 1000000000 to express it in seconds if (Input.keyDown(37)) this.velocityX -= speed * (timeDelta / 1000000000.0); if (Input.keyDown(39)) this.velocityX += speed * (timeDelta / 1000000000.0); if(Input.keyPressed(38)) { this.velocityY -= 6; } velocityY += g * (timeDelta/1000000000.0); //applying gravity move(velocityX, velocityY); /*this is method which moves a player according to velocityX and velocityY, and checking the collision */ this.velocityX = 0.0; } The strange thing is that when I have unlimited FPS (and update number) my player is jumping about 10 blocks. It jumps even higher when the FPS is increasing. If I limit FPS it is jumping 4 blocks. (BLOCK: 32x32) I have just realized that the problem is this:
if(Input.keyPressed(38)) { this.velocityY -= 6; } I add -6 to velocityY which increases player's Y proportionally to the update number and not to the time.
But I don't know how to fix this.
timeDelta / 1000000000.0all over the place. Compute that once when calculating your delta and just pass that through everywhere. Don't repeat yourself, don't perform unnecessary computations, and don't sprinkle your code with magic numbers. \$\endgroup\$