【Godot Engine】GDScriptから入力イベントを呼び出す

入力イベントをコード上から呼び出す

アクションイベント

# 押す
Input.action_press("ui_up")
# 離す
Input.action_release("ui_up")

InputEventクラスを使用して呼び出す場合

InputEventAction

アクションイベント

できることはInput.action_press、Input.action_releaseと同じ

var event = InputEventAction.new()
event.set_action("ui_up")
event.set_pressed(true)
Input.parse_input_event(event)

InputEventKey

キーボードイベント

InputEventAction( ui_up 等)に変換されて通知されるわけじゃないので、 InpuEventKey に対応したイベント処理を別途記述する必要がある。

var event = InputEventKey.new()
event.scancode = KEY_UP
event.pressed = true
Input.parse_input_event(event)

アクション名を動的に判断したい場合

アクション名はキーボードやジョイスティックの違いを吸収してくれ、 Godot のエディタ上で補完が効くので、基本アクション名で処理を書いていたほうが何かと都合がよさそうですが

どうしてもアクション名をその場に書きたくない場合、

現時点のバージョンでは、アクション名を逆引きできるメソッドがなさそうなため、登録済みのアクションを InputMap から取得してチェックする必要があります

# キーボード名からアクション名逆引き関数
func get_scancode_action_name(scancode):
    # アクション名を InputMap からすべて取得
    for action_name in InputMap.get_actions():
        # 各アクション名に紐づくイベントをすべてチェック
        for action in InputMap.get_action_list(action_name):
            # 対象のキーの場合
            if action is InputEventKey and action.scancode == scancode:
                return action_name
    return ""

# 呼び出し
Input.action_press(get_scancode_action_name(KEY_UP))