Godot Timing Tutorial

In this tutorial we will examine the various ways to implement timing in Godot.

Timing in the Game Loop

The _process(delta) function is called on every video frame such as 60 times per second. But there could be a different frame rate, so the time delay (delta) between frames is passed into the function. This is a float value of the number of seconds between frames so it’s likely to be around 0.0167 seconds.

Using the delta value, we may calibrate our speed of movement so that it will be the same for different fame rates e.g. position.x += SPEED * delta

It’s possible to code a timer using a variable to count the delta values and compare to a trigger time value as follows:

extends Node2D

signal timeout

const TIME_PERIOD = 0.5 # 500ms

var time = 0

func _process(delta):
	time += delta
	if time > TIME_PERIOD:
		# Reset timer
		time = 0

But, Godot provides the Timer Node and the SceneTreeTimer class to make it easy to set up timers.

Using the Timer Node

This is a Node that may be dropped into a Scene tree in the Editor and it’s properties edited to set the time delay and if it repeats etc. It outputs a timeout signal that we may connect to from another Node in our scene to handle the timeout event.

Also, we may spawn a Timer Node in code and set up it’s parameters. This is useful inside of an Autoload script that might need a timer for background loading of a large resource.

Example code:

extends Node

var timer

func _init():
	timer = Timer.new()
	timer.autostart = true
	timer.wait_time = 0.5
	timer.connect("timeout", self, "_timeout")

func _timeout():
	print("Timed out!")

Using the SceneTreeTimer

The SceneTreeTimer is used to create a one-shot delay timer that emits a timeout signal after the delay in seconds has elapsed. We may use the yield method to pause execution of code until it receives the signal as follows:

extends Node2D

func _ready():

func welcome():
	yield(get_tree().create_timer(1.0), "timeout")
	var popup = WindowDialog.new()
	popup.popup(Rect2(10, 10, 200, 200))
	yield(get_tree().create_timer(2.0), "timeout")

System Time

To get the amount of elapsed time in milliseconds since the engine started, use the OS.get_ticks() method.


I encourage You to try out these code examples to see how they work, and look at the Editor Node Tree and Output Window to really get a deep understanding of how the Timers work in Godot.

More solutions