Input examples

Introduction

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

Note

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

Events versus polling

Sometimes you want your game to respond to a certain input event - pressingthe "jump" button, for example. For other situations, you might want somethingto 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 inputevent occurs. In the second case, Godot provides theInputsingleton, which you can use to query the state of an input.

Examples:

func_input(event):ifevent.is_action_pressed("jump"):jump()func_physics_process(delta):ifInput.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 processingyou do.

For the remainder of this tutorial, we'll focus on capturing individualevents in_input().

Input events

Input events are objects that inherit fromInputEvent.Depending on the event type, the object will contain specific propertiesrelated to that event. To see what events actually look like, add a Node andattach the following script:

extendsNodefunc_input(event):print(event.as_text())

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

AMousemotionatposition((971,5))withvelocity((0,0))RightMouseButtonMousemotionatposition((870,243))withvelocity((0.454937,-0.454937))LeftMouseButtonMouseWheelUpABShiftAlt+ShiftAltShift+TMousemotionatposition((868,242))withvelocity((-2.134768,2.134768))

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

Tip

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

You can encounter errors if you try to access a property on an input type thatdoesn't contain it - callingposition onInputEventKey for example. Toavoid this, make sure to test the event type first:

func_input(event):ifeventisInputEventMouseButton:print("mouse button event at ",event.position)

InputMap

TheInputMap is the most flexible way to handle avariety of inputs. You use this by creating named inputactions, to whichyou 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 selectthe InputMap tab:

../../_images/inputs_inputmap.webp

Tip

A new Godot project includes a number of default actions already defined.To see them, turn onShowBuilt-inActions in the InputMap dialog.

Capturing actions

Once you've defined your actions, you can process them in your scripts usingis_action_pressed() andis_action_released() by passing the name ofthe action you're looking for:

func_input(event):ifevent.is_action_pressed("my_action"):print("my_action occurred!")

Keyboard events

Keyboard events are captured inInputEventKey.While it's recommended to use input actions instead, there may be cases whereyou want to specifically look at key events. For this example, let's check fortheT:

func_input(event):ifeventisInputEventKeyandevent.pressed:ifevent.keycode==KEY_T:print("T was pressed")

Tip

See@GlobalScope_Key for a list of keycodeconstants.

Warning

Due tokeyboard ghosting, not all key inputs may be registered at a given timeif 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 featureantighosting at a hardware level, but this feature is generallynot 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 wellon a keyboard without antighosting. Seethis Gamedev Stack Exchange questionfor more information.

Keyboard modifiers

Modifier properties are inherited fromInputEventWithModifiers. This allowsyou to check for modifier combinations using boolean properties. Let's imagineyou want one thing to happen when theT is pressed, but somethingdifferent when it'sShift+T:

func_input(event):ifeventisInputEventKeyandevent.pressed:ifevent.keycode==KEY_T:ifevent.shift_pressed:print("Shift+T was pressed")else:print("T was pressed")

Tip

See@GlobalScope_Key for a list of keycodeconstants.

Mouse events

Mouse events stem from theInputEventMouse class, andare separated into two types:InputEventMouseButtonandInputEventMouseMotion. Note that thismeans that all mouse events will contain aposition property.

Mouse buttons

Capturing mouse buttons is very similar to handling key events.@GlobalScope_MouseButtoncontains a list ofMOUSE_BUTTON_* constants for each possible button, which willbe reported in the event'sbutton_index property. Note that the scrollwheelalso counts as a button - two buttons, to be precise, with bothMOUSE_BUTTON_WHEEL_UP andMOUSE_BUTTON_WHEEL_DOWN being separate events.

func_input(event):ifeventisInputEventMouseButton:ifevent.button_index==MOUSE_BUTTON_LEFTandevent.pressed:print("Left button was clicked at ",event.position)ifevent.button_index==MOUSE_BUTTON_WHEEL_UPandevent.pressed:print("Wheel up")

Mouse motion

InputEventMouseMotion events occur wheneverthe mouse moves. You can find the move's distance with therelativeproperty.

Here's an example using mouse events to drag-and-drop aSprite2Dnode:

extendsNodevardragging=falsevarclick_radius=32# Size of the sprite.func_input(event):ifeventisInputEventMouseButtonandevent.button_index==MOUSE_BUTTON_LEFT:if(event.position-$Sprite2D.position).length()<click_radius:# Start dragging if the click is on the sprite.ifnotdraggingandevent.pressed:dragging=true# Stop dragging if the button is released.ifdraggingandnotevent.pressed:dragging=falseifeventisInputEventMouseMotionanddragging:# While dragging, move the sprite with the mouse.$Sprite2D.position=event.position

Touch events

If you are using a touchscreen device, you can generate touch events.InputEventScreenTouch is equivalent toa mouse click event, andInputEventScreenDragworks much the same as mouse motion.

Tip

To test your touch events on a non-touchscreen device, open ProjectSettings and go to the "Input Devices/Pointing" section. Enable "EmulateTouch From Mouse" and your project will interpret mouse clicks andmotion as touch events.


User-contributed notes

Please read theUser-contributed notes policy before submitting a comment.