+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.

asked Feb 25 in Engine by frob (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
answered Feb 25 by Mariothedog (154 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
answered Feb 25 by Zylann (26,157 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.