Calculate elapsed time using delta

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

I’m trying to sum delta until it reaches 5 seconds to do something, but it sums up faster than expecting. The code below prints timeout in less than 3 seconds passed.

const _max_delay = 5
const _current_delay = {}

func _process(delta):
	for c_delay in _current_delay.keys():
		_current_delay[c_delay] += delta
		if _current_delay[c_delay] >= _max_delay:

There is something wrong with the code above? I’m trying to avoid Timer node because it will be a lot of new instances at runtime.

That looks reasonable to me, though you don’t show how you’re initializing the Dictionary. I assume the keys that are added initially have a value of 0? Is there anything else that interacts with the values?

jgodfrey | 2023-01-13 03:14

:bust_in_silhouette: Reply From: GlitchedCode

There is no key in your _current_delay dictionary for c_delay to represent. Since it is a constant as well, this would mean that it can not be changed yes? So you can not add a new key into your dictionary. Try something like:

var start: bool = false
var max_time: int = 0
var my_timer: float = 0.0

func _process(delta):
    if start:
        my_timer += delta
    if my_timer >= max_time:
        start = false
        my_timer = 0.0
        print("Timer finished")

Not sure why it’s defined as a const, but it’s still possible to do something like:

const _current_delay = {}

func _ready():
	_current_delay["a"] = 0
	_current_delay["b"] = 0

jgodfrey | 2023-01-13 03:17

Actually, the problem was in the const variable. I have two instances running on the scene, and since const variables are at script level, the process compute sum twice in the same dictionary.

just change to var _current_delay did the trick. Thank you!

sandman | 2023-01-13 03:30