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?

asked Jun 28, 2016 in Engine by genete (672 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.

answered Jun 29, 2016 by CowThing (661 points)
selected Jun 29, 2016 by genete

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.