How to tell how long a button is pressed

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By frob

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.

:bust_in_silhouette: Reply From: Zylann

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

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?

MaaaxiKing | 2021-02-15 13:38