All Questions


Vinicius Vinhas

Multiplying by delta time

Hey Nathan! Why do you multiply the Y axis by delta on line 24 (when applying gravity) and not on the line 26 (jumping)? When should we multiply the velocity by delta?
  • Nathan Lovato replied

    Here, we're applying basic physics calculations to make our character move. It's a matter of making the units of each value match and producing a linear velocity, that is to say, a speed (in pixels per second) in a given direction.

    Our gravity is an acceleration (in pixels per second per second), so we need to multiply it by a time value (in seconds), here a time difference, delta, to turn it into a speed difference for this frame. Multiplied by a direction (Vector2.DOWN), it becomes a difference in linear velocity between last frame and this frame, so we can add it to our velocity.

    Regarding the more general question of when you should or shouldn't use delta, it depends. Use it when something should depend on the time difference between frames. Generally, you'll use it in movement to keep everything working with the same kind of logic, but you can also mix it with more arbitrary code as long as you get the result you need in the game.