Input examples

Introduction

In this tutorial, you'll learn how to use Godot's InputEvent system to capture player input. There are many different types of input your game may use - keyboard, gamepad, mouse, etc. - and many different ways to turn those inputs into actions in your game. This document will show you some of the most common scenarios, which you can use as starting points for your own projects.

Note

For a detailed overview of how Godot's input event system works, see Using InputEvent.

Events versus polling

Sometimes you want your game to respond to a certain input event - pressing the "jump" button, for example. For other situations, you might want something to happen as long as a key is pressed, such as movement. In the first case, you can use the _input() function, which will be called whenever an input event occurs. In the second case, Godot provides the Input singleton, which you can use to query the state of an input.

Examples:

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

This gives you the flexibility to mix-and-match the type of input processing you do.

For the remainder of this tutorial, we'll focus on capturing individual events in _input().

Input events

Input events are objects that inherit from InputEvent. Depending on the event type, the object will contain specific properties related to that event. To see what events actually look like, add a Node and attach the following script:

extends Node


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

As you press keys, move the mouse, and perform other inputs, you'll see each event scroll by in the output window. Here's an example of the output:

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))

As you can see, the results are very different for the different types of input. Key events are even printed as their key symbols. For example, let's consider InputEventMouseButton. It inherits from the following classes:

Tip

It's a good idea to keep the class reference open while you're working with events so you can check the event type's available properties and methods.

You can encounter errors if you try to access a property on an input type that doesn't contain it - calling position on InputEventKey for example. To avoid this, make sure to test the event type first:

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