+4 votes

How can I check for the user pressing the "K" or "S" keys? Not mapped, just raw named keys. This is in Godot3. I have this:

func _unhandled_input(ev):
  if (ev is InputEventKey and ev.??? == "K"):
    do_my_thing()

This seems like it should be simple, I'm probably missing something obvious.

asked Feb 11, 2018 in Engine by garyo (40 points)

2 Answers

+7 votes
Best answer
func _input(ev):
    if ev is InputEventKey and ev.scancode == KEY_K:
        #code

or

func _input(ev):
    if Input.is_key_pressed(KEY_K):
        #code

or if you want to run the code only once per press

func _input(ev):
    if ev is InputEventKey and ev.scancode == KEY_K and not ev.echo:
        #code

I do recommend using the input map though. Much easier.

answered Feb 12, 2018 by mateusak (1,076 points)
selected Feb 12, 2018 by garyo

Thanks -- this is helpful. When I hear "scancode" I think of something very different:
raw hardware key IDs like in https://en.wikipedia.org/wiki/Scancode. So I skipped over that, my mistake.

Just to be clear: is the difference between your first version (checking the InputEvent) and the second (Input.is_key_pressed) that the first one will only fire once, when the key is actually pressed (and again when it autorepeats), and the second will fire when any input event comes in (even mouse/touch/joystick), as long as the key is currently pressed?
Also, does echo actually mean it's an autorepeat? (Rather than the actual keypress)

If this is all correct, I'll submit a pull request for some doc updates to http://docs.godotengine.org/en/stable/classes/class_inputevent.html#class-inputevent-is-echo

Yes, everything you just said is correct. If you move your mouse for example the Input.is_key_pressed will fire your code more often as long as you press the key. And echo is in fact an 'autorepeat'. It is better described here.

Particularly, I find _input is often unnecessary, I mostly check inputs in the physics_process, because it's not only much easier and prettier, but some inputs like the mouse do not echo, so it's really hard to know if a player is still shooting for example if you use _input.

+1 vote

Here's how I do it:

func _ready():
    set_process_input(true) 
    ##This may or may not be required for inputs to work.

func _input(ev):
    if Input.is_key_pressed(KEY_K):
        do_your_thing()

I don't really know how to use the ev thing.

You can do KEYS or KEYENTER or KEYKP5 for 5 on the numpad, and lots more.

For more keyboard buttons to use, check this link out and scroll down:
http://docs.godotengine.org/en/3.0/classes/class_@globalscope.html

Hope this helps.

answered Feb 12, 2018 by Sdhy (55 points)

You don't need to set_process_input in Godot 3.0, it detects it automatically.

That's convenient. Thanks!

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.