Timers & Tweens
Two small tools remove most hand-written "count down a float in _process" code:
- a timer fires a signal after a delay: spawn waves, weapon cooldowns, invincibility frames, "respawn in 3 seconds";
- a tween animates a property from its current value to a target over time with an easing curve: a coin popping up, a menu sliding in, a hit flash, a camera zoom.
Both run on the scene tree's clock, so they respect pause and Engine.time_scale. In the examples below the test runner fixes the frame rate at 60 FPS, so 0.25 s is exactly 15 frames.
Timer nodes and SceneTree timers
Timer node |
get_tree().create_timer(sec) |
|
|---|---|---|
| Lives | as a child node; reusable | as a temporary SceneTreeTimer object; one use |
| Repeats | yes, unless one_shot |
no |
Can stop, restart, read time_left |
yes | time_left only |
| Best for | cooldowns, spawners, anything repeated or cancelled | "do this once, in N seconds", usually with await |
extends Node
# frames: 70
var spawn_timer: Timer
var spawned := 0
func now() -> String:
return "frame %d (%.2f s)" % [Engine.get_process_frames(), Engine.get_process_frames() / 60.0]
func _ready():
spawn_timer = Timer.new()
spawn_timer.wait_time = 0.25
spawn_timer.autostart = true # starts when it enters the tree
spawn_timer.timeout.connect(_on_spawn)
add_child(spawn_timer)
var fuse := Timer.new()
fuse.wait_time = 0.5
fuse.one_shot = true
fuse.timeout.connect(func(): print(now(), ": fuse done, time_left=", fuse.time_left))
add_child(fuse)
fuse.start()
get_tree().create_timer(1.0).timeout.connect(func(): print(now(), ": one-off SceneTree timer"))
print("started, fuse time_left=", fuse.time_left)
func _on_spawn() -> void:
spawned += 1
print(now(), ": spawn #", spawned)
if spawned == 3:
spawn_timer.stop()
print(" spawner stopped, is_stopped=", spawn_timer.is_stopped())started, fuse time_left=0.5
frame 15 (0.25 s): spawn #1
frame 30 (0.50 s): spawn #2
frame 30 (0.50 s): fuse done, time_left=0.0
frame 45 (0.75 s): spawn #3
spawner stopped, is_stopped=true
frame 59 (0.98 s): one-off SceneTree timer
Notes:
autostartonly takes effect when the timer enters the tree; a timer created in code and added later withautostart = falseneedsstart().start(2.0)also sets a newwait_time.- A repeating timer fires every
wait_timeuntilstop(). Its frame-exact timing comes fromprocess_callback(idle frames by default; setTIMER_PROCESS_PHYSICSto tick with physics). - The
SceneTreeTimerfired at frame 59, not 60: the tree updates its own timers at a different point in the frame thanTimernodes. Timers are accurate to a frame, not finer; never depend on the order of two timers that end in the same frame. - A timer can't fire more than once per frame. For a weapon firing 100 shots per second at 60 FPS, accumulate time yourself instead.
create_timer(sec, process_always, process_in_physics, ignore_time_scale): the extra arguments control pausing and time scale. With the defaultprocess_always = true, a SceneTreeTimer keeps running while the game is paused. Passfalsefor gameplay delays.
Tweens
Create tweens with create_tween() on a node: the tween is bound to that node, pauses with it and dies with it. Each tween_* call appends a step. Steps run one after another by default; set_parallel(true) (or parallel() before one step) runs them together, and chain() goes back to sequence.
extends Node2D
# frames: 75
var coin: Node2D
func _ready():
coin = Node2D.new()
coin.name = "Coin"
add_child(coin)
var tw := create_tween()
tw.tween_property(coin, "position:y", -40.0, 0.4).set_trans(Tween.TRANS_QUAD).set_ease(Tween.EASE_OUT)
tw.tween_interval(0.1)
tw.tween_callback(func(): print(" callback: coin at top, y=", coin.position.y))
tw.set_parallel(true)
tw.tween_property(coin, "scale", Vector2(0.0, 0.0), 0.3)
tw.tween_property(coin, "modulate:a", 0.0, 0.3)
tw.chain().tween_callback(coin.queue_free)
tw.finished.connect(func(): print("finished at frame ", Engine.get_process_frames()))
func _process(_delta):
var f := Engine.get_process_frames()
if f % 6 == 0 and is_instance_valid(coin):
print("frame ", f, ": y=", snappedf(coin.position.y, 0.01), " scale=", snappedf(coin.scale.x, 0.01), " alpha=", snappedf(coin.modulate.a, 0.01))frame 0: y=0.0 scale=1.0 alpha=1.0
frame 6: y=-17.5 scale=1.0 alpha=1.0
frame 12: y=-30.0 scale=1.0 alpha=1.0
frame 18: y=-37.5 scale=1.0 alpha=1.0
frame 24: y=-40.0 scale=1.0 alpha=1.0
frame 30: y=-40.0 scale=1.0 alpha=1.0
callback: coin at top, y=-40.0
frame 36: y=-40.0 scale=0.67 alpha=0.67
frame 42: y=-40.0 scale=0.33 alpha=0.33
frame 48: y=-40.0 scale=0.0 alpha=0.0
finished at frame 48
Reading the numbers:
TRANS_QUAD+EASE_OUTstarts fast and slows down: after a quarter of the time (frame 6) the coin has already risen 17.5 of 40 pixels (1 − 0.75² = 0.4375). Linear motion would be at 10. Transitions name the curve (LINEAR,SINE,QUAD,CUBIC,EXPO,ELASTIC,BOUNCE,BACK,SPRING...), eases say which end is gentle (IN,OUT,IN_OUT,OUT_IN)."position:y"and"modulate:a"tween a single component of a property through a sub-property path.- Scale and alpha shrink together because they are parallel steps; the callback after
chain()waits for both. tween_callback(coin.queue_free)passes the method itself as aCallable; no lambda needed.tween_property(...).from(value)sets an explicit start value,as_relative()makes the target an offset (+40from wherever it is), andset_delay()delays one step.
Restarting, looping and awaiting
A tween runs until it finishes or is killed. Starting a second tween on the same property while the first is still running makes them fight. Keep a reference and kill() the old one:
extends Node2D
# frames: 40
var hit_tween: Tween
func flash() -> void:
if hit_tween and hit_tween.is_valid():
hit_tween.kill() # restart instead of stacking two tweens
print(" killed the running flash")
modulate = Color.RED
hit_tween = create_tween()
hit_tween.tween_property(self, "modulate", Color.WHITE, 0.2)
func _ready():
var pulse := create_tween().set_loops(3)
pulse.tween_property(self, "rotation_degrees", 10.0, 0.05)
pulse.tween_property(self, "rotation_degrees", 0.0, 0.05)
pulse.loop_finished.connect(func(n): print(" pulse loop ", n, " done"))
flash()
await get_tree().create_timer(0.1).timeout
print("hit again at frame ", Engine.get_process_frames(), ", modulate.g=", snappedf(modulate.g, 0.01))
flash()
await hit_tween.finished
print("flash finished at frame ", Engine.get_process_frames(), ", modulate=", modulate) pulse loop 1 done
hit again at frame 6, modulate.g=0.5
killed the running flash
pulse loop 2 done
flash finished at frame 18, modulate=(1.0, 1.0, 1.0, 1.0)
set_loops(3)repeats the whole sequence three times;set_loops()with no argument loops forever (set_loops(0)), so make sure such a tween is bound to a node that eventually dies, or kill it.loop_finishedfires after every loop except the last, which emitsfinished.await tween.finished(see await & Coroutines) writes sequences top to bottom: flash, wait, then continue.- Tweens start by themselves on the next frame; there is no
play()to forget. Add all steps in the same function: a tween that starts with no steps reports an error and is invalid. Tween.set_process_mode(Tween.TWEEN_PROCESS_PHYSICS)animates physics bodies in step with physics;set_pause_mode(Tween.TWEEN_PAUSE_PROCESS)keeps menu animations running while the game is paused.
Tween or AnimationPlayer?
Use a tween for animations decided at runtime: the target depends on gameplay (move to the clicked cell, count the score up to the new value, shake by an amount). Use an AnimationPlayer (AnimationPlayer & AnimatedSprite2D) for authored animations with many keys and tracks that an artist edits on a timeline.
Test yourself
Which tool fits "fire the turret every 0.8 s until it is destroyed"?
get_tree().create_timer(0.8)once- A
Timernode withwait_time = 0.8, not one-shot, connected to a fire method - A tween with
set_loops() awaitin_process
In a tween, how do you make two property changes happen at the same time?
- Call
create_tween()twice on the same property - Use
set_parallel(true)(orparallel()) for those steps - Steps are always parallel
- Use
tween_interval(0)
A hit flash tween is started again while the previous one is running. What is the clean fix?
- Nothing, tweens merge automatically
- Keep a reference and call
kill()on the old tween before creating the new one - Use
set_loops(0) - Free the node