Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Godot Keyboard Events

I am studying the Godot Engine and GDScript and I searched on the internet about keyboard events, but I didn't understand. Is there something in Godot like: on_key_down("keycode")?

like image 714
user193464 Avatar asked Sep 04 '17 22:09

user193464


People also ask

How do I add actions to Godot?

To add an action, write its name in the bar at the top and press Enter. Create the five actions. Your window should have them all listed at the bottom. To bind a key or button to an action, click the "+" button to its right.

How can I tell if a key is pressed in Godot?

You can use Input. is_action_just_pressed("key") to see if it was just pressed, and Input. is_action_pressed("key") to see if it is still pressed.

How do you deal with inputs in Godot?

To receive input at the time it happens (button down, key pressed, mouse moved), use _input , or _unhandled_input if you have GUI nodes in your game. To poll input anytime or every frame, use the Input singleton.

What is Godot GDScript?

GDScript is a dynamically typed scripting language made specifically for free and open source game engine Godot. GDScript's syntax is similar to Python's. Its main advantages are ease of use and tight integration with the engine. It's a perfect fit for game development.


2 Answers

There's no official OnKeyUp option, but you can use the _input(event) function to receive input when an action is pressed/released:

func _input(event):

    if event.is_action_pressed("my_action"):
        # Your code here
    elif event.is_action_released("my_action):
        # Your code here

Actions are set in Project Settings > Input Map.

Of course you don't always want to use _input, but rather get inputs within the fixed updates. You can use Input.is_key_pressed() but there's no is_key_released(). In that case you can do this:

var was_pressed = 0

func _fixed_process(delta):
    if !Input.is_key_pressed() && was_pressed = 1:
        # Your key is NOT pressed but WAS pressed 1 frame before
        # Code to be executed

    # The rest is just checking whether your key is just pressed
    if Input.is_key_pressed():
        was_pressed = 1
    elif !Input.is_key_pressed():
        was_pressed = 0

That's what I've been using. Feel free to inform me if there's a better way to do OnKeyUp in Godot.

like image 88
theducvu Avatar answered Oct 18 '22 14:10

theducvu


Godot versions 3.0 and up have new input-polling functions that can be used anywhere in your scripts:

  • Input.is_action_pressed(action) - checks if the action is being pressed
  • Input.is_action_just_pressed(action) - checks if the action was just pressed
  • Input.is_action_just_released(action) - checks if the action was just released
like image 23
surfboardipod Avatar answered Oct 18 '22 15:10

surfboardipod