Timing a certain period when a button just pressed

quy_nguyenquy_nguyen Posts: 2Member

Hi all developers,
I am not sure what is the correct way to do this so I need help to proceed it. I am making a car game where there is a shifting mechanism. So every time the "A" key is pressed, after 0.5s, a gear shift up. Any way to approach this?? Thank youu :>


  • TwistedTwiglegTwistedTwigleg Posts: 2,847Admin

    Welcome to the forums @quy_nguyen!

    Something like this should work (untested):

    var action_timer = 0
    func _process(delta):
        if (action_timer > 0):
            action_timer -= delta
            if (action_timer <= 0):
    func start_timer():
        action_timer = 0.5 # this will be 0.5 seconds

    The example above just shows the relevant bits for the timer, with variables named accordingly. You'll likely want to give them more descriptive names so its easier to understand.

    You can also probably use a Timer node, though I personally haven't used them that often so I cannot say right off what code would be needed to make it work.

  • AzedaxenAzedaxen Posts: 41Member

    I like to use yield(get_tree(create_timer(0.5), "timeout")). This line will pause code execution until the time specified in create_timer() passes. One thing to be wary of however; when you yield this way, Godot will keep checking to see if the amount of time has passed. If your node gets deleted before it can continue the code execution for whatever reason, Godot will throw an error when the code would've resumed, as it's trying to resume execution on an object that no longer exists. It's usually not a fatal error that will prevent the game from working, but still something to keep in mind. If you need to get around this error, I would recommend the method above.

  • quy_nguyenquy_nguyen Posts: 2Member

    Thank youu @TwistedTwigleg & @Azedaxen <3

Sign In or Register to comment.