How to avoid key typing repetition?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By genete
:warning: Old Version Published before Godot 3 was released.

I have the following code for a node:

extends Node2D


func _ready():
	set_process(true)
	pass

func _process(delta):
	var add_credit=Input.is_action_pressed("add_credit")
	if add_credit:
		get_node("/root/global").credits+=1
	update_credit_value()

func update_credit_value():
	get_node("Value").set_text(str(get_node("/root/global").credits).pad_zeros(2))

If I press the key that correspond to “add_credit” action, the credit increases to 5 or 6 instantly. How do I avoid that and read one key input at a time?

:bust_in_silhouette: Reply From: CowThing

You’re checking if “add_credit” is pressed every frame, so if you tap the button you will probably tap it for multiple frames, and if you hold the button down you will increase it every frame. So instead of using _process() you’ll want to use _input() so you can trigger the adding only once when the button is pressed.

extends Node2D

func _ready():
	set_process_input(true)

func _input(event):
	if event.is_action_pressed("add_credit"):
		get_node("/root/global").credits+=1
		update_credit_value()

func update_credit_value():
	get_node("Value").set_text(str(get_node("/root/global").credits).pad_zeros(2))

Edit: This is not correct, read the comments for the proper way.

That would trigger it every frame either. You need to check if it’s an echo.

extends Node2D

func _ready():
    set_process_input(true)

func _input(event):
    if event.is_action_pressed("add_credit") and not event.is_echo():
        get_node("/root/global").credits+=1
        update_credit_value()

func update_credit_value():
    get_node("Value").set_text(str(get_node("/root/global").credits).pad_zeros(2))

mateusak | 2016-06-29 00:18

Ah yes, you’re right, I was mistaken.

CowThing | 2016-06-29 00:35

Thank you CowThing and mateusak for the quick and detailed reply!

genete | 2016-06-29 06:11

Why this statement not work in mouse button click event like this?`

func _input(event):
	
if (event.is_action_pressed("mouse_left_click")):
	print ("OK")

where “mouse_left_click” is defined in InputMap Project Settings.
Thanks
-j

jospic | 2016-06-29 11:11

Note that in Godot 4 is_action_pressed has a 2nd argument allow_echo that is false by default.

Hyper Sonic | 2023-05-18 20:44