+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 (42 points)

1 Answer

+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 (28,738 points)

I also thought GUI Buttons were the question topic, however, that's not why I write this comment; I think it would be great if it could be set in the Editor because it's way easier for how long a button stays pressed because of the visuals, what do y'all think?

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.