Delta Time in Godot

By: Cam Wohlfeil
Published: 2017-07-27 0000 EDT
Modified: 2018-09-19 1230 EDT
Category: Programming
Tags: godot, gamedev

The Godot docs don't cover delta in any great detail and maybe they shouldn't, but understanding delta time is important in game programming since it helps your game gain framerate independence. If you don't already know, tying game logic and physics to framerate is easy but gives you undesired behavior like setting hard limits on what frame rate your game can run at, causing collision bugs if you do try to get your game running at higher framerates, or movement/actions speeding up and slowing down with framerate. All of these create a terrible user experience, especially on PCs and modern consoles where 60+ fps is the norm. In Godot, you'll mostly see delta when passing it in as a parameter to the _process overrideable functions, like so:

func _ready():
    set_process(true)

func _process(delta):
    # do something every frame

func _fixed_process(delta):
    # do something every physics frame

Delta is the time in seconds since the last frame. Since games normally run at at least 30fps and usually 60fps, that means this will be a float type showing milliseconds, and it will NOT be constant since frame latency varies widely. It will look like 0.017, 0.020, 0.01, etc.

To take advantage of delta time, all you have to do is normalize it. If you want an action to happen 60 times per second, it's a simples as action_speed * delta! Here's an examples pulled straight from the Godot docs:

# Code trimmed to just show the key bits
# Initial direction of the ball
var direction = Vector2(1.0, 0.0)
# Constant for pad speed (in pixels/second)
const INITIAL_BALL_SPEED = 80
# Speed of the ball (also in pixels/second)
var ball_speed = INITIAL_BALL_SPEED

func _process(delta):
    var ball_pos = get_node("ball").get_position()

ball_pos += direction * ball_speed * delta

Assuming our ball is moving in a straight horizontal line from the origin (the top left corner) at it's initial speed and with a delta of .20 (50fps), this means our will move at a rate of Vector2(0.0, 0.0) + (Vector2(1.0, 0.0) * 80 * .02) = Vector2(1.6, 0.0) or 1.6 pixels to the right every frame. But what if the framerate is higher? Let's try 100fps: Vector2(0.0, 0.0) + (Vector2(1.0, 0.0) * 80 * .01) = Vector2(16.0, 0.0) or 0.8 pixels to the right every frame. What about 25 fps? Vector2(0.0, 0.0) + (Vector2(1.0, 0.0) * 80 * .04) = Vector2(3.2, 0.0) or 3.2 pixels to the right every frame. Pretty simple concept once you lay it out!

As a note, physics should usually not be tied to delta time since the calculations require much more precise timing. Godot handles this already, so it's not something you need to worry about unless you start changing physics speed in the project settings.

P.S. - If you don't remember vectors, they're also super important in game programming. Check out Math for Game Developers on YouTube.

References