Godot 键盘事件

Godot Keyboard Events

我正在研究Godot Engine和GDScript,在网上搜索了键盘事件,但没看懂。 Godot 中是否有这样的东西:on_key_down("keycode")?

您可以使用 InputEvent 检查特定的键。

查看文档:http://docs.godotengine.org/en/stable/learning/features/inputs/inputevent.html

没有官方的 OnKeyUp 选项,但您可以使用 _input(event) 函数在操作为 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

在项目设置 > 输入地图中设置操作。

当然,您并不总是想使用 _input,而是希望在固定更新中获取输入。您可以使用 Input.is_key_pressed(),但没有 is_key_released()。在这种情况下,您可以这样做:

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

这就是我一直在使用的。如果在 Godot 中有更好的方法 OnKeyUp,请随时告诉我。

Godot 3.0 及更高版本具有新的输入轮询功能,可在您的脚本中的任何位置使用:

  • Input.is_action_pressed(action) - 检查动作是否被按下
  • Input.is_action_just_pressed(action) - 检查动作是否被按下
  • Input.is_action_just_released(action) - 检查动作是否刚刚发布

如果您正在考虑使用 Input 或 _Input(event),请务必进入您的项目设置并绑定您的密钥。

按工具栏中的项目设置,转到输入地图,然后您可以命名一个动作并向其添加任何键、鼠标或操纵杆。在代码中使用:

if Input.is_action_just_pressed('Your action name'):
   print('Pressed!')

where is project settings button