Bad Dev
Bad Dev

Reputation: 25

How to make a timer count up ever second then reset to 0 when the character dies

So, I made a game where you dodge drones as an Alien and I need help on adding a feature where the timer (Called PlayerTimer,located in the player node) counts up every time you are alive, then when the character dies it resets to 0. Right now, I've tried to look thing up but nothing is happening.

Here's what I have in my Main scene, my text is called TimerUI and my Timer is called PlayerTimer

.

Upvotes: 1

Views: 1166

Answers (1)

congbinh
congbinh

Reputation: 61

The timer node only counting down. Assume you're using Godot 4 with GDScript, you could use function Time.get_ticks_msec() to get current time counted from when the engine started in miliseconds:

onready var timer_ui = $TimerUI
var is_counting = false
var start_time
var elapsed_time_in_sec

func set_timer(is_start):
    if is_start:
        is_counting = true
        start_time = Time.get_ticks_msec()
    else:
        is_counting = false
        elapsed_time_in_sec = 0
        timer_ui.text = elapsed_time_in_sec

func _process(delta):
    if is_counting:
        elapsed_time = floor((Time.get_ticks_msec() - start_time) / 1000)
        timer_ui.text = elapsed_time_in_sec

Here you can call set_timer() to start the timer when is_start is true and stop it when it's false.

Upvotes: 1

Related Questions