Godot键盘事件

use*_*464 3 keyboard-events gdscript godot

我正在研究Godot Engine和GDScript,并且我在互联网上搜索了有关键盘事件的信息,但我听不懂。Godot中是否有类似的东西on_key_down("keycode")

小智 10

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

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


小智 8

没有官方的 OnKeyUp 选项,但您可以使用该_input(event)函数在按下/释放操作时接收输入:

func _input(event):

    if event.is_action_pressed("my_action"):
        # Your code here
    elif event.is_action_released("my_action):
        # Your code here
Run Code Online (Sandbox Code Playgroud)

操作在项目设置 > 输入映射中设置。

当然,您并不总是想使用_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
Run Code Online (Sandbox Code Playgroud)

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


小智 5

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

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

  • 按下按键,按下按键和仅按下按键有什么具体要求吗? (2认同)