+1 vote

I want the player to keep a button pressed for 2 seconds. If success, something happens.
If not (the button is pressed for less than 2 seconds), something else happens.
How do you do that?

I've tried with timers, incremental variables, combining “if not press” within “if pressed” without success.

in Engine by (58 points)

1 Answer

0 votes
Best answer

it ocurred to me 10 minutes after posting it haha
this is the solution that worked for me if anyone needs it

func track_time_button():
    var button_time = 2
    if Input.is_action_just_pressed("a"):
        $timer.start(button_time)
    if Input.is_action_just_released("a"):
        $timer.stop()
        print('fail')


func _on_timer_timeout():
    print('success')
by (58 points)
selected by

This will always print "fail" though when the key is released, no matter the hold-time.

If the one_shot -property of your timer is set, you can do:

if Input.is_action_just_released("a"):
    if not $timer.is_stopped():
        $timer.stop()
        print('fail')

If not, it's a little bit more verbose, but still easy to solve:

var success = false

func track_time_button():
    var button_time = 2
    if Input.is_action_just_pressed("a"):
        $timer.start(button_time)
    if Input.is_action_just_released("a"):
        $timer.stop()
        if success:
            success = false
        else:
            print('fail')


func _on_timer_timeout():
    print('success')
    success = true

On a side note your second if should really be an elif: it's impossible that the same key is simultaneously pressed and released during one frame.

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 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 webmaster@godotengine.org with your username.