Checking how LONG a key is being held down

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

This is a stupid question but how do you check how LONG a key is being held down?? Currently in my game right now, I am trying to check if the E key is being held down for at least 2 seconds in order to pick up an object but I don’t know how to do so. If someone asked the same question and has a solution to it, please send me the link or the explanation. Thank you

:bust_in_silhouette: Reply From: jgodfrey

There are a number of ways you could do that depending on the details of what you want. Here’s an example of one.

var total = 0

func _process(delta):
	if Input.is_action_pressed("ui_up"):
		total += delta
	
	if Input.is_action_just_released("ui_up"):
		total = 0

	if total > 2:
		total = 0
		print("Up held for 2 seconds")

As long as your action (“ui_up” above) is being held, a running total of time is tracked. If it exceeds some value (2 seconds above), a messages is printed. If the key is released or the goal time is met, the total is reset.

Thank you! This was exactly what I was looking for. But why exactly r u incrementing “total” by delta?

jiwooyun_ | 2022-12-18 21:36

The delta variable tracks the length of time that has passed since the previous call to _process(). So, by adding those up in each frame, you can get a “running total” of elapsed time…

jgodfrey | 2022-12-18 21:42