Topic was automatically imported from the old Question2Answer platform.
Asked By
Serenade
Old Version
Published before Godot 3 was released.
Hi
I want to use timer node for attack function, and other things later, but
I have zero idea how to use it, and information online didnt help at all.
How can i write code, that it starts counting time, for example, from when i press X button, and then when it has reached, 2 second, only then X button becomes active again… or suggest your way, plz?
The class reference does not have examples of use, a page with examples for each class could be good to have (but not on reference), anyway…
Somewhere, like in _ready:
timer = Timer.new()
timer.connect("timeout",self,"_on_timer_timeout")
#timeout is what says in docs, in signals
#self is who respond to the callback
#_on_timer_timeout is the callback, can have any name
add_child(timer) #to process
timer.start() #to start
Then, on the connected node (self in this case, could be the parent or any other node in the scene)
func _on_timer_timeout():
your_timer_stuff()
thanks for this explanation. i assume that the last line should be timer.start(delay), with delay a float to specify after how many seconds the timer should trigger?
i just spent quite some time being confused why the timer did not work until i realized that for the start call to actually do anything, the node where you add the timer to needs to already be in the scene tree. i was instantiating a node, setting up a timer inside that node and then added the node into the tree. does not work that way (imho start() should trigger an error in this case), but does work when doing it the other way round, first adding the node, and only then starting the timer.
Actually in code, if you want, you don’t have to use the Timer node Godot provides. Here’s an alternative way.
A simple timer:
var timer = 0
func _process(delta):
timer += delta
When timer reached certain time, you can simply add an if statement. Or using signal for better control:
var timer = 0
var wait_time = 1
signal timeout
func _on_timeout():
#Your code
func _process(delta):
timer += delta
if timer > wait_time:
timer = 0
emit_signal("timeout")
For more control, create more variables like disabled (Like when the timer hasn’t started) and code (Anything you want)
Why the way adding delta on timer works:
delta means the time passed since the last call of _process().
So each time _process() is being called, the timer will be updated.