How to make player recover health progressively?

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

I am making a 2d game with Godot engine, and I need my player to recover health progressively (waits some seconds, and then, it increases health by 1).
How could I achieve somehing like this?

:bust_in_silhouette: Reply From: lufemas

Take a look on the Timer node

But how could I make it loop to check if health is not full, then wait, and recover health?. Cause I’ve tried with a while true: loop in _ready(): , but it crashes

SebSharper | 2020-04-01 20:23

But how could I make it loop to check if health is not full, then wait, and recover health?

That’s called “busy-waiting” and rarely is a good idea. If you setup a Timer and connect it’s timeout-signal to a function, this function will called on every timeout.

var health = 5
const MAX_HEALTH = 5

func _on_Timer_timeout():
    if health < MAX_HEALTH
        health += 1

Cause I’ve tried with a while true: loop in _ready():

Never try this again! The _ready-function is called when a node enters the tree. If it runs forever (because you’re running a while(true)-loop in it), that’s all your node will be able to do for the full length of the game. You don’t want this. Ever.

njamster | 2020-04-01 21:18

Take a look on signals: Signals — Godot Engine (3.2) documentation in English

Then you look the Timer: Timer — Godot Engine (3.2) documentation in English

There is a lot of youtube tutorials on signals and Timer. Basically the Timer emits a signal when the time is over and you can call a functional when this signal is emitted. This function you restore the health or whatever and start the Timer again if the health is not full yet. Then whenever ‘health < FULL_HEALTH’ you can start the Timer.

lufemas | 2020-04-01 23:49