InputEvent in Godot – Complete Guide

Welcome to our comprehensive guide on the InputEvent class in Godot 4. As you embark on your game development journey, knowing how to handle user input is crucial. It is through this interaction that players connect with your game, making mastering InputEvents an essential part of creating an immersive gaming experience. Whether you’re taking your first steps in Godot or you’re a seasoned developer looking to hone your skills, this introductory tutorial will walk you through the foundational concepts of InputEvents in Godot 4.

What is InputEvent in Godot?

InputEvent serves as an abstract base class for all types of input events within the Godot game engine. From tapping on a touchscreen to pressing a key on the keyboard, InputEvents capture these user actions so they can be translated into game mechanics, UI interactions, and more.

How Does InputEvent Work?

Derived from the Resource class, InputEvent comes in many forms – including actions, joystick motions, mouse button clicks – and provides an API to precisely manage each form of input. Understanding how to work with these events is key to customizing player controls and responding to their actions effectively.

Why Should You Learn About InputEvent?

By mastering InputEvents, you gain the power to craft responsive and engaging game controls that can be tailored to specific gameplay scenarios. This knowledge is fundamental for would-be developers to elevate the playability of their games, making this an essential subject to learn and understand in the realm of game development.

CTA Small Image

Handling Key Presses with InputEventKey

One of the most common forms of input is through key presses on a keyboard. Let’s dive into how you can detect and respond to key presses using the InputEventKey class in Godot 4.

func _input(event):
    if event is InputEventKey:
        if event.pressed and event.scancode == KEY_SPACE:
            print("The space bar was pressed!")

This snippet demonstrates the basic structure for detecting when the space bar is pressed. An instance of InputEventKey includes properties such as pressed and scancode that indicate the state of the key and which key was pressed. We check these to determine the appropriate action.

Responding to Mouse Clicks

Mouse interactions often involve clicking buttons or interacting with GUI elements. The following example shows how to detect a left mouse click using the InputEventMouseButton class.

func _input(event):
    if event is InputEventMouseButton:
        if event.button_index == BUTTON_LEFT and event.pressed:
            print("Left mouse button clicked!")

The above code detects a left mouse button click by checking the button_index and ensuring the button is actually being pressed down, not just released.

Working with Joystick Input

Games often require joystick input, particularly for character movement or navigation in menus. Here’s how you can respond to joystick movement using the InputEventJoypadMotion class.

func _input(event):
    if event is InputEventJoypadMotion:
        if event.axis == JOY_AXIS_0:
            print("Joystick moved on the x-axis with value: ", event.axis_value)

Joystick input can be more complex, as it involves axes and values instead of simple button presses. This code checks if the joystick moves along the x-axis (horizontal movement) and prints the degree of this movement.

Detecting Touch Events

For games on mobile or touchscreen devices, detecting touch input is essential. Here you’ll see how to handle a touch event with the InputEventScreenTouch class.

func _input(event):
    if event is InputEventScreenTouch:
        if event.pressed:
            print("Screen was touched at position: ", event.position)

This code snippet will print the screen position where the user’s touch was detected. Notice that event.position gives us the coordinates of the touch, which can be vital for touch-based gameplay.

All these examples show the simplicity yet flexibility of the Godot 4 input system. Understanding how each of these classes and their properties work allows you to finely control how your game responds to various player inputs, creating a smooth and intuitive gaming experience.

Now let’s delve deeper into some advanced usage scenarios of InputEvents to handle game mechanics like dragging and double-clicking, manipulating text input, and customizing input handling.

Handling drag actions is essential in many games, especially when interfacing with inventory systems or UI elements. Below is an example of how to implement a drag mechanic using InputEventMouseMotion.

var is_dragging = false

func _input(event):
    if event is InputEventMouseButton:
        if event.button_index == BUTTON_LEFT:
            is_dragging = event.pressed

    if is_dragging and event is InputEventMouseMotion:
        print("Dragging at position: ", event.position)

This example checks for a mouse button press to initiate dragging and then tracks mouse movement to determine where the user is dragging an item on the screen.

Double-clicking is another common feature, often needed for opening files in a GUI or firing a weapon in a game. To implement a double-click, you can do something like this:

var last_click_time = 0

func _input(event):
    if event is InputEventMouseButton:
        if event.button_index == BUTTON_LEFT and event.pressed:
            var time_since_last_click = OS.get_ticks_msec() - last_click_time
            if time_since_last_click < 300:  # time in milliseconds
                print("Double clicked!")
            last_click_time = OS.get_ticks_msec()

This code tracks the time between two left mouse button clicks and prints “Double clicked!” if the interval is below 300 milliseconds.

Games that require text input for chatboxes or character naming screens need to handle InputEventKey differently, here’s one way to do it:

func _input(event):
    if event is InputEventKey:
        if event.pressed and not event.echo:
            var unicode = event.get_unicode()
            if unicode != 0:
                var character = char(unicode)
                print("Character typed: ", character)

event.get_unicode() is used to convert the key input into a Unicode character, which allows for the capturing of a broader scope of characters beyond the basic ASCII set, including characters from different languages.

Lastly, let’s look at how you might customize the handling of InputEvents for a particular node. By setting mouse_filter to MOUSE_FILTER_STOP, for instance, you can ensure that a UI element intercepts mouse input events and prevents them from propagating to other elements beneath it.

func _ready():

func _gui_input(event):
    if event is InputEventMouseButton and event.button_index == BUTTON_LEFT and event.pressed:
        print("UI element clicked!")

In this example within a Control-derived node, the _gui_input function is used instead of _input. This is specifically for handling GUI events, and it allows for more nuanced control when working with UI nodes.

These examples illustrate a variety of ways to manipulate InputEvents in Godot 4, showcasing the engine’s flexibility in responding to a broad array of input types. By understanding and utilizing these building blocks, developers can create highly interactive and dynamic experiences tailored to their specific gameplay needs.

Let’s explore further with more complex interactions such as combo key pressing, handling analog input for smooth character movement, customizing input with Input Map, and capturing gestures for touch-based devices.

Recognizing combination key presses, such as ‘Ctrl+C’ for copy actions, can be achieved by checking the status of modifier keys alongside regular keys.

func _input(event):
    if event is InputEventKey:
        if event.pressed and event.scancode == KEY_C and event.control:
            print("Copy command activated!")

This snippet checks if the ‘C’ key is pressed while the control modifier is active, which might correspond to a copy command in a game or application context.

Processing analog input, such as from a gamepad’s trigger or stick for nuanced character movement, can add depth to gameplay. Here’s how:

func _input(event):
    if event is InputEventJoypadMotion:
        if event.axis == JOY_AXIS_2:
            var intensity = event.axis_value

func move_character(intensity):
    print("Moving character with intensity: ", intensity)

Analog input allows for variable input strength, represented by axis_value, which can be used to control movement speed or intensity.

It might become necessary to define or change input actions within your game. Godot’s Input Map allows for this customization:

func _ready():

func _input(event):
    if Input.is_action_just_pressed("jump"):
func jump():
    print("Player jumped!")

By adding a new action called ‘jump’ and binding it to the spacebar, we create a customizable input action that can be queried within scripts, maintaining a level of abstraction between the physical key and the action performed.

In mobile games, capturing swipe gestures can be integral to the control scheme:

var start_position = Vector2()
var end_position = Vector2()

func _input(event):
    if event is InputEventScreenDrag:
        start_position = event.position - event.relative
        end_position = event.position

func _process(delta):
    if start_position.distance_to(end_position) > 20:
        handle_swipe(start_position, end_position)
        start_position = end_position

func handle_swipe(start, end):
    var direction = end - start
    print("Swipe detected! Direction: ", direction)

Starting and ending positions of touch events are tracked to detect and handle swipe gestures, critical in many touch-based games for directional input or page swiping in menus.

For keyboard-and-mouse PC games, right-click context menus are a common feature. Here’s an example of how to implement a basic right-click context menu system:

func _input(event):
    if event is InputEventMouseButton:
        if event.button_index == BUTTON_RIGHT and event.pressed:
            var click_position = event.position

func open_context_menu(position):
    # Imagine opening a context menu at the mouse position
    print("Right-click menu opened at: ", position)

This snippet looks for right mouse button presses and opens a hypothetical context menu function at the click’s position, which could overlay buttons or options for the player to select.

By dissecting and employing InputEvents in these ways, developers can craft tailored and responsive experiences in Godot 4. Thinking creatively about how players interact with the game world, you can build control systems that feel natural, intuitive, and fun to use.

Continue Your Game Development Journey

Your adventure in mastering InputEvents within Godot 4 doesn’t end here. Whether you’re just getting started or looking to advance your skills further, our Godot Game Development Mini-Degree offers a treasure trove of knowledge to help you continue your learning journey. This comprehensive collection of courses will guide you through various aspects of game creation using the Godot engine, equipping you with the tools to build your own unique games, from the ground up.

Our courses are meticulously designed for flexible learning, allowing you to grasp the intricacies of game development at your own pace. From understanding the basics of 2D and 3D game development to exploring complex gameplay systems, our curriculum ensures a thorough learning experience. You’ll come away with tangible projects that not only bolster your understanding but also enhance your portfolio.

If you’re eager to explore an even broader range of topics and projects, we invite you to discover our full suite of Godot courses. With our in-depth tutorials and comprehensive content, you can transform from a beginner to a professional game developer in the Godot engine. Embrace the opportunities waiting in the thriving games market, and start crafting your path in game development today.


In the vast universe of game development, understanding the pulsing heart of player interaction—InputEvents—is a monumental step in bringing your gaming visions to life. Throughout this guide, we’ve navigated the seas of key presses, mouse clicks, joystick jockeying, and touch inputs. Each concept explored is a vital link in the chain of immersive game experiences, empowering you to create not just games but worlds that engage and captivate your audience.

As you continue to experiment and innovate with Godot 4, remember that knowledge is a beacon in the creation process. Keep shining bright by delving into our Godot Game Development Mini-Degree, where each lesson hammers home the expertise required to master this craft. Galvanize your game development skills with us, and let’s elevate your projects from dreams to reality together.

Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.