Keep track of the time a player is pressing a button

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

I want the player to keep a button pressed for 2 seconds. If success, something happens.
If not (the button is pressed for less than 2 seconds), something else happens.
How do you do that?

I’ve tried with timers, incremental variables, combining “if not press” within “if pressed” without success.

:bust_in_silhouette: Reply From: hermo

it ocurred to me 10 minutes after posting it haha
this is the solution that worked for me if anyone needs it

func track_time_button():
	var button_time = 2
	if Input.is_action_just_pressed("a"):
		$timer.start(button_time)
	if Input.is_action_just_released("a"):
		$timer.stop()
		print('fail')


func _on_timer_timeout():
	print('success')

This will always print “fail” though when the key is released, no matter the hold-time.

If the one_shot -property of your timer is set, you can do:

if Input.is_action_just_released("a"):
    if not $timer.is_stopped():
        $timer.stop()
        print('fail')

If not, it’s a little bit more verbose, but still easy to solve:

var success = false

func track_time_button():
	var button_time = 2
	if Input.is_action_just_pressed("a"):
		$timer.start(button_time)
	if Input.is_action_just_released("a"):
		$timer.stop()
		if success:
			success = false
		else:
			print('fail')


func _on_timer_timeout():
	print('success')
	success = true

On a side note your second if should really be an elif: it’s impossible that the same key is simultaneously pressed and released during one frame.

njamster | 2020-02-05 18:34

:bust_in_silhouette: Reply From: DavidPeterWorks

I would do this.
The success/fail happens only one time / button selection.
_on_Button_button_down() and _on_Button_button_up connected to the buttons’s signal.
$Timer is a timer node.

var is_down = false
var no_more = false
onready var timer = $Timer



func _ready():
	timer.wait_time = 2
	timer.one_shot = true
    timer.autostart = false

    
func _physics_process(delta):

    if no_more:
            return

	if is_down and timer.is_stopped():
		no_more = true
		success()

	if !is_down and !timer.is_stopped():
		timer.stop()
		fail()


func _on_Button_button_down():
	is_down = true
	timer.start()
	
	

func _on_Button_button_up():
	is_down = false
    no_more = false