+1 vote

Hi I have recently tried to create a countdown timer to show the time remaining for the action to occur but my way seems to be lengthy and inefficient.

var time_total = 0
var time_dict = {"D" : 0, "H" : 0, "M" : 0, "S" : 0}


func start_time(given_time):
    time_total = given_time * 3600 # into secs
    convert_time()

func convert_time():
    var time = time_total

    while time >= 60: # get minutes
        time -= 60
        time_dict["M"] += 1

    time_dict["S"] = time # rest is seconds

    while time_dict["M"] >= 60:
        time_dict["M"] -= 60
        time_dict["H"] += 1

    while time_dict["H"] >= 24:
        time_dict["H"] -= 24
        time_dict["D"] += 1

    print(time_dict)

is there any better way

in Engine by (940 points)
edited by

1 Answer

0 votes
Best answer

I tried to do something more readable:

var start_time
var duration

func set_start_time():
    start_time = OS.get_unix_time() #the time at the moment in seconds

func time_convert(time_in_sec):
    var seconds = time_in_sec%60
    var minutes = (time_in_sec/60)%60
    var hours = (time_in_sec/60)/60

    #returns a string with the format "HH:MM:SS"
    return "%02d:%02d:%02d" % [hours, minutes, seconds]

func elapsed_time():
    var elapsed_time = OS.get_unix_time() - start_time #actual time - start time

func get_remainnging_time():
    return duration - elapsed_time()
by (79 points)
selected by
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.