0 votes

I am working to create something similar to a TextEdit, and for that I setup an input function to detect when a key is pressed:

func _input(event):
    if event is InputEventKey:
        if event.is_pressed():
            var key_pressed = ... #detect which key is pressed
            text += key_pressed

That's basically what I want to do (I can handle the backspace separately), I have found that I can use the event.scancodeto get a code representing the character which is pressed, and what I want to know is how to know which key was originally pressed using the scancode or anything else.

Thanks in advance

asked 4 days ago in Engine by PugMasterPug (89 points)

1 Answer

0 votes

GlobalScope has an enum of scancodes called KEY_*. For example, KEY_A = 65.

You can use this to do something like:

if event is InputEventKey:
    if event.scancode == KEY_A:
        # do stuff

If you're checking lots of keys you can use a match statement or a dictionary here.

If you have the scancode and want to know the name of the key you can use OS.get_scancode_string() which will return the "name" of the key as a string, i.e. “Escape”, “Shift+Escape”. OS.find_scancode_from_string() does the opposite.

answered 4 days ago by kidscancode (4,536 points)

At the end I did the following:

var character = char(event.unicode)
print(character)

A much better solution to the problem

If you're only dealing with ASCII key inputs. However, be aware that if you have a scancode with modifiers (capital vs. lowercase, for example), unicode input, or other non-character keypresses, char() won't work.

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.