How to decrease value of variable overtime?

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

I’m trying to create a destroyable object that requires the player to hold down a button for a specific amount of time to destroy the object.

The object has a health variable, I want to use this to play an animation depending on how much health it has.

The player also has an Area2D which detects the body of the breakable object (StaticBody2D), when it does detect it, it emits the breakable objects signal “hit”.

I then want to connect the “hit” signal to a function that decreases the health variable depending on how long that signal is being relayed (or is there another way to do this…?)

How could I achieve this?

can you post some code of your setup?

There are many ways to archive this … but what fits best depends on your setup.

klaas | 2020-08-27 08:54

I haven’t quite set up anything yet, I’m just playing around with how I can achieve this.
Right now this is the script for the breakable object:

extends StaticBody2D

var hp = 3

func destroyed():

func hit():
    hp -= 1
    if hp <= 0:

And here is what I have for the player:

func _on_Drillbox_body_entered(body):
if body == breakable:

Pneuma | 2020-08-27 09:02

:bust_in_silhouette: Reply From: klaas

this is a quite simple approach

var hit_timer =

func _on_Drillbox_body_entered(body):
    if body == breakable:
       #connect the timer signal to the breakable hit function   
       #whenever the timer reached its timelimit hit gets called
       hit_timer.start(0.5) #hit him every 0.5 s

func _on_Drillbox_body_exited(body):
    if body == breakable:
       #if your player leaves the area
       #disconnect the signal
       #stop the timer

consider reading the first tutorial its quite usefull, gives you an insight on how to do the basic stuff

I was just thinking about how it would probably be best to use a timer, thanks!

Pneuma | 2020-08-27 09:34