Hello! How do I restore a player's stamina with a delay? If I use await, the player freezes because the code is in _physics_process. I want stamina recovery to start after sprinting after 2 seconds.
Stamina recovery with delay
- Edited
Here's how I'd attempt this instead from my newb-ish status:
get_tree().create_timer(2.0).timeout.connect(func():
my_restore_stamina_logic()
)
If you prefer to start the recovery in _process or physics, then I'd say you need to invent some instance variable such as time_sprinting_last_stopped
and check in _process whether that is longer ago than 2s. If other dynamics affect your stamina state however, that might quickly become unwieldy / inscrutable =)
- Edited
- Best Answerset by Azlalzalala
I think meta_leap has the right idea. Easier to count down than up though. Something like this:
extends Node2D
@export var stamina_wait_time := 2.
var stamina := 100.
var stamina_cooldown := 0.
##anywhere that uses stamina should do so through this function
func use_stamina(p_stamina:float) -> void:
stamina -= p_stamina
stamina_cooldown = stamina_wait_time
func regenerate_stamina() -> void:
#code to regenerate your stamina goes here
func _process(delta: float) -> void:
if stamina_cooldown > 0.:
stamina_cooldown -= delta
if stamina_cooldown <= 0.:
regenerate_stamina()
I find doing this sort of thing all in _process easier than with a Timer, because with a Timer you'd need to reset it every time you use stamina as well as stop whatever process was regenerating stamina. Ends up being more you need to manage than just a simple float. Timers have other great use cases but usually when you know you want something to happen for sure, or when it only needs to happen once or happens periodically every X seconds.
award Thank you very much!
meta_leap Thank you very much!