0 votes

I want to make a reflex game where you have to press the right arrow key when the button shows up on screen.
There is a penalty if you press the wrong arrow, and I also want to trigger it when the player press any other key on the keyboard.

I tried to use event.ispressed() in a function _unhandledkeyinput(event), BUT the thing is that event.ispressed seems to be true not only when a key is pressed, but also when it is long pressed or when it is released.

here is my function :

func _unhandled_key_input(event):
if etat==etats.ATTENTE and event.is_pressed():
    if event.is_action_pressed("ui_up"):
        test("haut")
        print("UP")
    if event.is_action_pressed("ui_down"):
        test("bas")
        print("DOWN")
    if event.is_action_pressed("ui_left"):
        test("gauche")
        print("LEFT")
    if event.is_action_pressed("ui_right"):
        test("droite")
        print("RIGHT")
    else:
        faux()
        print("not an arrow...")
    etat = etats.VERIF
    get_tree().set_input_as_handled()

the functions test() is meant to test if an input is right (and I think this part of the code works well). The function faux() is called to show a feedback to the player that it's wrong and change the arrow.

About the outputs I am getting :
- When it says "RIGHT" "LEFT" "UP" or "DOWN", it was always what I typed.
- sometimes, even with a brief press in the good direction, it prints the good direction and "not an arrow"... But not each time !
- when I press multiple arrows, it prints the directions and "not an arrow" sometimes
- when I press an other key, it prints "not an arrow"

I hope I am clear enough !

asked May 21 in Engine by Leonis Curiosity (12 points)
recategorized May 21 by Leonis Curiosity

1 Answer

+1 vote

You have to use elif. Otherwise all if-statements are evaluated one after the other and the else-case will apply whenever you're not pressing ui_right.

the thing is that event.is_pressed seems to be true not only when a key is pressed, but also when it is long pressed or when it is released.

Yes, if you hold a key, it will emit a new InputEvent each frame where pressed is true. But no, if you release the key, that won't be the case - that's the idea!

However, event.is_action_pressed will only be true during the first frame the key is pressed. It has an optional second argument allow_echo that you can set to true, if you want to change this. By default it's false, so if you hold down a key, it will output the correct direction in the first frame, but print "not an arrow..." in all other frames, as this is not explicitly checking if the key's scancode isn't an arrow key.

answered May 22 by njamster (8,788 points)

it worked !
thank you

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.