A clean way to call a function repeatedly for a set duration?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By epark009

I would like to implement a way to call a function repeatedly for a specified duration. For example, when a character gets hit, they will shake randomly for 0.5 seconds. Currently, I have the shake occur in _physics_process that will start and stop based on a boolean, a function that turns off the boolean when the timer runs out, and yet another function for starting the timer and turning on the boolean. Is there a cleaner way to do this? Ideally, the Timer node should just keep running the shake function until it times out, but there doesn’t appear to be a way to do that.

:bust_in_silhouette: Reply From: Calinou

Ideally, the Timer node should just keep running the shake function until it times out, but there doesn’t appear to be a way to do that.

You could have a counter variable that’s initialized to an positive integer and is decremented every time the timer times out. Once it reaches zero, the timer stops.

:bust_in_silhouette: Reply From: Dlean Jeans

I’d create a scene/node just for that.
Call it Shaking or something. Move your code and Timer node here.
When the character gets hit, call:

character.add_child(Shaking.instance())

After 0.5 seconds when the Timer is up, queue_free() the node.
This way, the character scene is cleaner.

This also applied to other effects like powerups: speed-up, invincibility,…