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?

Hi,
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

Hi,
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():
    self.queue_free()

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

And here is what I have for the player:

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

Pneuma | 2020-08-27 09:02

:bust_in_silhouette: Reply From: klaas

this is a quite simple approach

var hit_timer = Timer.new()

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.connect("timeout",body,"hit") 
       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
       hit_timer.disconnect("timeout",body,"hit")
       #stop the timer
       hit_timer.stop()

consider reading the first tutorial its quite usefull, gives you an insight on how to do the basic stuff
https://docs.godotengine.org/en/stable/getting_started/step_by_step/your_first_game.html

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

Pneuma | 2020-08-27 09:34