0 votes

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?

in Engine by (679 points)

1 Answer

0 votes
Best answer

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.

by (665 points)
selected by

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))

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

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

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

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.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.