+1 vote

How would I go about detecting how long a button has been pressed. I can use Input.is_action_pressed to determine which action is pressed but I cannot tell how to see how long a button has been pressed.

in Engine by (20 points)

2 Answers

+1 vote

You could use Input.is_action_just_released.

var duration = 0

func _physics_process(delta):
    if Input.is_action_pressed("ui_accept"):
        duration += delta

    if Input.is_action_just_released("ui_accept"):
        duration = 0
by (156 points)
+1 vote

Edit: sorry, i thought you mentionned GUI buttons^^


There are several ways depending on what you want to do with this.

Connect signals button_down and button_up, memorize the time it was when it gets down, and when it gets up, do the difference between current time and memorized time:

var _time_when_pushed_down = 0

func _on_Button_button_down():
    _time_when_pushed_down = OS.get_ticks_msec()

func _on_Button_button_up():
    var duration_pressed = (OS.get_ticks_msec() - _time_when_pushed_down) / 1000.0

Another way is to accumulate delta while it's pressed:

var _duration_pressed = 0

func _pressed():
    # Reset time when it becomes pressed
    _duration_pressed = 0

func _process(delta):
    if pressed:
        _duration_pressed += delta
by (27,164 points)
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.

Categories