Up to date

This page is up to date for Godot 4.2. If you still find outdated information, please open an issue.

入力の例

はじめに

このチュートリアルでは、GodotのInputEvent システムを使用してプレイヤーの入力をキャプチャする方法を学習します。ゲームで使用できる入力には、キーボード、ゲームパッド、マウスなど、さまざまな種類があり、それらの入力をゲームのアクションに変換するさまざまな方法があります。このドキュメントでは、最も一般的なシナリオをいくつか紹介します。これらのシナリオは、独自のプロジェクトの出発点として使用できます。

注釈

Godotの入力イベントシステムの動作の詳細については、Using InputEvent を参照してください。

イベント対ポーリング

特定の入力イベントにゲームを応答させたい場合があります - たとえば、「ジャンプ」ボタンを押します。他の状況では、移動など、キーが押されている限り何かを実行したい場合があります。最初のケースでは、入力イベントが発生するたびに呼び出される _input() 関数を使用できます。 2番目の場合、Godotは Input シングルトンを提供します。これを使用して、入力の状態を照会できます。

例:

func _input(event):
    if event.is_action_pressed("jump"):
        jump()


func _physics_process(delta):
    if Input.is_action_pressed("move_right"):
        # Move as long as the key/button is pressed.
        position.x += speed * delta

これにより、実行する入力処理のタイプを自由に組み合わせることができます。

このチュートリアルの残りの部分では、_ input() で個々のイベントをキャプチャすることに焦点を当てます。

入力イベント

入力イベントは、InputEvent を継承するオブジェクトです。イベントタイプに応じて、オブジェクトにはそのイベントに関連する特定のプロパティが含まれます。イベントが実際にどのように見えるかを確認するには、ノードを追加し、次のスクリプトをアタッチします:

extends Node


func _input(event):
    print(event.as_text())

キーを押したり、マウスを動かしたり、他の入力を実行したりすると、出力ウィンドウで各イベントがスクロールして表示されます。出力の例を次に示します:

A
Mouse motion at position ((971, 5)) with velocity ((0, 0))
Right Mouse Button
Mouse motion at position ((870, 243)) with velocity ((0.454937, -0.454937))
Left Mouse Button
Mouse Wheel Up
A
B
Shift
Alt+Shift
Alt
Shift+T
Mouse motion at position ((868, 242)) with velocity ((-2.134768, 2.134768))

ご覧のとおり、結果は入力の種類によって大きく異なります。キーイベントはキーシンボルとしても印刷されます。たとえば、InputEventMouseButton を考えてみましょう。次のクラスから継承します:

  • InputEvent - すべての入力イベントの基本クラス

  • InputEventWithModifiers - ShiftAlt などのモディファイヤが押されているかどうかをチェックする機能を追加します。

  • InputEventMouseposition などのマウスイベントプロパティを追加します

  • InputEventMouseButton - 押されたボタンのインデックス、ダブルクリックかどうかなどが含まれます。

ちなみに

イベントの操作中は、イベントの種類で使用可能なプロパティとメソッドを確認できるように、クラス参照を開いたままにすることをお勧めします。

InputEventKeyposition を呼び出すなど、その型を含まない入力型のプロパティにアクセスしようとすると、エラーが発生する可能性があります。これを回避するには、まずイベントタイプをテストしてください:

func _input(event):
    if event is InputEventMouseButton:
        print("mouse button event at ", event.position)

入力マップ

The InputMap is the most flexible way to handle a variety of inputs. You use this by creating named input actions, to which you can assign any number of input events, such as keypresses or mouse clicks. To see them, and to add your own, open Project -> Project Settings and select the InputMap tab:

../../_images/inputs_inputmap.webp

ちなみに

A new Godot project includes a number of default actions already defined. To see them, turn on Show Built-in Actions in the InputMap dialog.

アクションのキャプチャ

アクションを定義したら、探しているアクションの名前を渡すことで is_action_pressed()is_action_released() を使用してスクリプトでアクションを処理できます:

func _input(event):
    if event.is_action_pressed("my_action"):
        print("my_action occurred!")

キーボードイベント

キーボードイベントは InputEventKey でキャプチャされます。代わりに入力アクションを使用することをお勧めしますが、重要なイベントを具体的に調べたい場合もあります。この例では、T を確認します:

func _input(event):
    if event is InputEventKey and event.pressed:
        if event.keycode == KEY_T:
            print("T was pressed")

ちなみに

See @GlobalScope_Key for a list of keycode constants.

警告

Due to keyboard ghosting, not all key inputs may be registered at a given time if you press too many keys at once. Due to their location on the keyboard, certain keys are more prone to ghosting than others. Some keyboards feature antighosting at a hardware level, but this feature is generally not present on low-end keyboards and laptop keyboards.

As a result, it's recommended to use a default keyboard layout that is designed to work well on a keyboard without antighosting. See this Gamedev Stack Exchange question for more information.

キーボード・モディファイヤ

モディファイヤのプロパティは、InputEventWithModifiers から継承されます。これにより、ブールプロパティを使用してモディファイヤの組み合わせを確認できます。T が押されたときに起こることが1つあり、Shift + T のときは何か違うことが起こると想像してみましょう。

func _input(event):
    if event is InputEventKey and event.pressed:
        if event.keycode == KEY_T:
            if event.shift_pressed:
                print("Shift+T was pressed")
            else:
                print("T was pressed")

ちなみに

See @GlobalScope_Key for a list of keycode constants.

マウスイベント

マウスイベントは InputEventMouse クラスから派生し、2つのタイプに分けられます: InputEventMouseButton および InputEventMouseMotion です。これは、すべてのマウスイベントに position プロパティが含まれることを意味することに注意してください。

マウスボタン

Capturing mouse buttons is very similar to handling key events. @GlobalScope_MouseButton contains a list of MOUSE_BUTTON_* constants for each possible button, which will be reported in the event's button_index property. Note that the scrollwheel also counts as a button - two buttons, to be precise, with both MOUSE_BUTTON_WHEEL_UP and MOUSE_BUTTON_WHEEL_DOWN being separate events.

func _input(event):
    if event is InputEventMouseButton:
        if event.button_index == MOUSE_BUTTON_LEFT and event.pressed:
            print("Left button was clicked at ", event.position)
        if event.button_index == MOUSE_BUTTON_WHEEL_UP and event.pressed:
            print("Wheel up")

マウスモーション

InputEventMouseMotion イベントは、マウスが移動するたびに発生します。relative プロパティで移動の距離を確認できます。

Here's an example using mouse events to drag-and-drop a Sprite2D node:

extends Node


var dragging = false
var click_radius = 32 # Size of the sprite.


func _input(event):
    if event is InputEventMouseButton and event.button_index == MOUSE_BUTTON_LEFT:
        if (event.position - $Sprite2D.position).length() < click_radius:
            # Start dragging if the click is on the sprite.
            if not dragging and event.pressed:
                dragging = true
        # Stop dragging if the button is released.
        if dragging and not event.pressed:
            dragging = false

    if event is InputEventMouseMotion and dragging:
        # While dragging, move the sprite with the mouse.
        $Sprite2D.position = event.position

タッチイベント

タッチスクリーンデバイスを使用している場合、タッチイベントを生成できます。InputEventScreenTouch はマウスクリックイベントに相当し、InputEventScreenDrag はマウスの動きとほぼ同じように機能します。

ちなみに

非タッチスクリーンデバイスでタッチイベントをテストするには、プロジェクト設定を開き、"Input Devices/Pointing" セクションに進みます。 "Emulate Touch From Mouse" を有効にすると、プロジェクトはマウスクリックとモーションをタッチイベントとして解釈します。