Making health lower by the second (like a bleed effect) but can be increased when entering a specific area

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

I’m trying to use a timer to make the players health lower by the second but I’m having trouble increasing their health (like picking up a potion).
This is the code for the health bar
extends Control

var health = 100
func _ready():
    $bleed_timer.wait_time = health
    $bleed_timer.start()

func life_change(health):
    $ProgressBar.value = health
func _process(delta):
    $ProgressBar.value = $bleed_timer.time_left

func _on_bleed_timer_timeout():
    health -= 5

And this is what I put in the players script to make the health increase one an area is entered

func _on_interactionarea_body_entered(body):
    if body.name == "blood pack":
        $Camera2D/healthbar.health += 20

Is there a better way to do this or how can I achieve this? I want the players health to degrade by the second but increase when picking up an item yet the health still decreases after gaining the health.
Any help is welcomed, thank you.

You’ve explained what you’re trying to do, but not the actual problem you’re having with it (at least, I don’t see a problem explanation). Are you getting an error? Is the increase in health just not working (with no error)? Something else entirely?

Generally, the idea decreasing the health on a timer and increasing it when/where appropriate is perfectly fine.

jgodfrey | 2022-10-28 13:53

:bust_in_silhouette: Reply From: Wakatta

if the health increase is a one time only also connect the body_exited signal

#Healthbar.gd
extends Control

var health = 100
var health_max = 100

func _ready():
    $bleed_timer.wait_time = 1 #second
    $bleed_timer.start()

func life_change(amt):
    health += amt

   #prevent health from going over 100 and under 0
    health = clamp(health, 0, health_max)

    $ProgressBar.value = health

func _on_bleed_timer_timeout():
    life_change(-5)

#Player.gd
func _on_interactionarea_body_entered(body):
    if body.name == "blood pack":
        $Camera2D/healthbar/bleed_timer.stop()
        $Camera2D/healthbar.life_change(20)

func _on_interactionarea_body_exited(body):
    if body.name == "blood pack":
        $Camera2D/healthbar/bleed_timer.start()

Tips for the future

Don’t use _process unless you need a reoccurring action
Do use reactive actions instead (something happens because something happened)

Don’t update visuals and variables separately
Do change variables first then reflect that change visually

Don’t always rely on using $node or get_node() everywhere
Do assign them to variables instead in cases where you decide to rename nodes you won’t have to refactor your entire code, only the line with the assignment

Example

var health_bar = $Camera2D/healthbar
var bleed_timer = $bleed_timer