How to detect which key is pressed?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By PugMasterPug

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

:bust_in_silhouette: Reply From: kidscancode

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.

At the end I did the following:

var character = char(event.unicode)

A much better solution to the problem

PugMasterPug | 2018-07-12 20:24

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.

kidscancode | 2018-07-12 20:35

:bust_in_silhouette: Reply From: hungrymonkey

You can add custom names for key codes in the godot.project settings

Project → Project Settings → Input Map → “custom_space” → add action → then add the scancode to the text field

func _input(event): if Input.is_action_just_pressed("custom_space" ):

the is_action_just_press is not rendering property. code blocks just seem broken…

:bust_in_silhouette: Reply From: ruruarchy

something like this :

func _input(ev):
        if ev is InputEventKey :

or this also

func _input(ev):
        if ev is InputEventKey :

it will print 2x on pressing a key, 1 for pressed 1 for released

ruruarchy | 2019-06-25 09:30

we could also print it only once by adding

and ev.is_pressed == true :


and ev.is_pressed == false :

in if statement
the former is at press state
the latter is at released state

ruruarchy | 2019-06-25 09:36

:bust_in_silhouette: Reply From: AciD

With Godot 4 this has changed.
Now to get the “scancode”, you need to do:

func _input(event):
	if event is InputEventKey:
		if event.keycode == KEY_ESCAPE:
			# Code here