Timer for each level godot3.1

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

I want to set a timer for each level of my game, so that when the player eats item number one, 10 seconds will be added to the time of that level, and when the player eats item number two, 5 seconds will be subtracted from the time of that level. The total playing time in each level should be 60 seconds. How can I script it?

And to display the timer in the scene of each level (60:00), should I use a special command?

:bust_in_silhouette: Reply From: Venex2004
  1. Firstly create a time scene so each level can inherit and manipulate the timer.
  2. Then learn to convert your time left(Timer must have started) for your timer to minutes and second or whatever suits you.
  3. Then for when player eats an item, you can’t add to time to a timer that has already started. So I suggest that you stop what ever time that is active the add or subtract from the time left then start the timer again.
    Note - You need to get the time left before adding or subtracting else the time left will return a Nill or 0.
    Hope these solve your questions
:bust_in_silhouette: Reply From: godot_dev_

@Venex2004’s answer is good. Here is code that may help you display the time remaining from your timer in a label, where every _process call the script will check the time remaining in the timer, calculate the time remaining, and then display it in a label mm:ss format (if you ever decide to increase the time beyond 60 seconds, e.g., 1:45) and s format (e.g., 32) when less than 1 minute is remaining:

var timer = null
var timeLabel = null
func _process(delta):
    #compute the time remaining
    var secondsRemaining = timer.time_left     
    var secondsOverAMinute = secondsRemaining % SECONDS_PER_MINUTE
    var minutes = secondsRemaining/SECONDS_PER_MINUTE
	#format the time string
    var string = ""       
    if minutes > 0:            		
        #mm:ss format
        string = str(minutes) +":"+str(secondsOverAMinute)             
        #s format
    #update the label that displays the time
    timeLabel.text = str(string)

Keep in mind the above code could be further optimized, instead of running that logic every _process call, you could execute the logic only when 1 second goes by

godot_dev_ | 2023-04-24 16:27