InputEventScreenTouch in Godot – Complete Guide

Welcome to our deep dive into the world of Godot 4 and its InputEventScreenTouch class. Touch input is a cornerstone of modern game design, particularly for mobile games, where it serves as the primary method of player interaction. Understanding how to handle touch events efficiently can make the difference in crafting a responsive and engaging game. In this tutorial, we’ll explore what InputEventScreenTouch is, unpack its properties, and see how it can be utilized within Godot to create immersive touch-based gameplay experiences.

What is InputEventScreenTouch?

InputEventScreenTouch is a class in the Godot Engine responsible for handling multi-touch input events. These events include various touch interactions like pressing, releasing, or detecting a double tap on the screen. The ability to handle these touch events in Godot is crucial for developing games that feel interactive and intuitive on devices with touchscreens.

What is it Used for?

InputEventScreenTouch is used for capturing and responding to touch input from the players. This could involve anything from moving characters, triggering actions, and navigating through the game’s UI. Game developers can fine-tune how their games react to touch, creating smooth and natural interactions that enhance the player’s experience.

Why Should I Learn It?

As mobile gaming continues to rise in popularity, understanding touch input handling is an essential skill for game developers. Mastering the InputEventScreenTouch class allows you to design your game for a broad audience and ensures that your controls are as intuitive as possible. Learning this can also open up new possibilities for creativity in game design and can be the difference between a good game and a great one.

CTA Small Image

Handling Basic Touch Events in Godot 4

Let’s start with the essentials of capturing touch events in Godot. Ensure your project is set up with the latest version of Godot 4 to make use of its updated features. We’ll handle the press and release of a touch event within a node’s _input function.

func _input(event):
    if event is InputEventScreenTouch:
        # Check if the screen was touched.
        if event.is_pressed():
            print("The screen has been touched!")
            print("The touch has ended!")

This code snippet demonstrates the detection of a touch press and release. When the touch begins, is_pressed() will return true, and when the touch ends (a release), it will be false.

Detecting Touch Position

Moving forward, you might want to know where on the screen the touch event took place. Position information is crucial for things like moving characters or interactive UI elements.

func _input(event):
    if event is InputEventScreenTouch and event.is_pressed():
        var touch_position = event.position
        print("Touch at position: ", touch_position)

The position property provides a Vector2 value representing the touch’s coordinates on the screen. We only print the position when the screen is initially touched, avoiding a log on release.

Working with Multi-touch

Most modern touch devices support multi-touch, allowing several fingers to be detected simultaneously. Godot can also handle this through the index property of the InputEventScreenTouch class.

func _input(event):
    if event is InputEventScreenTouch:
        var touch_index = event.index
        if event.is_pressed():
            print("Finger", touch_index, "touched at", event.position)
            print("Finger", touch_index, "released from", event.position)

This example tracks which finger was used for the touch event, enabling you to distinguish between multiple touches.

Implementing Touch Dragging

Drag gestures are a common requirement for touch interaction. For that purpose, we need to track the movement of the touch across the screen.

In Godot, you would usually handle dragging with the InputEventScreenDrag class, but for illustrative purposes, let’s simulate a simple drag using InputEventScreenTouch and the _input method.

var last_touch_position = Vector2()

func _input(event):
    if event is InputEventScreenTouch:
        if event.is_pressed():
            last_touch_position = event.position
            var drag_distance = event.position - last_touch_position
            print("Dragged distance: ", drag_distance)
            last_touch_position = Vector2()

This code will track the drag distance by comparing the position of touch release to the last touch position. It’s a basic form of drag detection, typically enhanced with momentum and other factors in production code.

In the next part, we will delve deeper into implementing more advanced touch functionalities like gesture recognition and building a responsive touch-based control scheme. Stay tuned for further techniques that will advance your Godot touch input handling skills!

Moving beyond basic touch events, let’s dive into some advanced ways you can leverage the InputEventScreenTouch class in Godot 4 to create a touch-rich gaming environment.

To achieve a full-fledged touch system, we would need to include gesture recognition, multitouch with gestures, pinch and zoom, as well as a swiping mechanism. Let’s explore these one by one.

Gesture Recognition

Recognizing gestures is crucial for a natural user interface. For simplicity, we’ll look at distinguishing between a single tap and a double tap using InputEventScreenTouch.

var last_tap_time = OS.get_ticks_msec()

func _input(event):
    if event is InputEventScreenTouch:
        if event.is_pressed():
            var current_time = OS.get_ticks_msec()
            if current_time - last_tap_time < 300: # 300 milliseconds for double tap
                print("Double Tap detected at ", event.position)
                print("Single Tap")
            last_tap_time = current_time

We measure the time between two successive tap events to detect a double tap. This recognizes rapid consecutive touches as a gesture.

Multi-touch with Gestures

Handling multiple touches might also involve recognizing simultaneous taps. This is more complex and requires tracking of all active touches.

var active_touches = []

func _input(event):
    if event is InputEventScreenTouch:
        if event.is_pressed():
            print("Finger", event.index, "down at", event.position)
            print("Finger", event.index, "up from", event.position)

We keep a list of active touches, adding to it when a touch starts and removing when a touch ends. Using this data, we can later interpret specific gesture patterns.

Pinch and Zoom

Pinch and zoom is a user input technique typically used for scaling images or maps. We would need to track two touch points and calculate the distance between them as they move.

func _input(event):
    if event is InputEventScreenTouch and event.is_pressed():
        # Assuming two fingers are always used for pinch and zoom
        if active_touches.size() == 2:
            var touch1 = active_touches[0].position
            var touch2 = active_touches[1].position
            var distance = touch1.distance_to(touch2)
            # Use signal or direct function call to scale your object here

This example assumes that the actions for pinch and zoom will only occur with two fingers. We compare the distance between two touch points to decide whether to zoom in or out.

Swipe Mechanics

A swipe gesture allows the user to quickly drag across the screen. A typical application would be a carousel menu or switching between different UI screens.

var start_touch_position = Vector2()
var end_touch_position = Vector2()

func _input(event):
    if event is InputEventScreenTouch:
        if event.is_pressed():
            start_touch_position = event.position
            end_touch_position = event.position
            var swipe_vector = start_touch_position - end_touch_position
            if swipe_vector.length() > 50: # Minimum swipe distance
                print("Swipe detected with vector: ", swipe_vector)

Here, we track the start and end position of a swipe, ensuring a minimum distance is swiped for this action to be a recognized gesture. This way, you can define further actions based on the swipe’s direction and force.

By implementing these advanced touch input mechanics, your game will not only cater to the basic need for touch interaction but elevate the end-user experience to a more intuitive and sophisticated level. Game development in Godot 4 with a solid understanding of touch input is an essential skill for providing players with high-quality, interactive mobile gaming experiences.

Using the code examples provided, you can experiment with each feature to see how it works in practice. Remember that refinement and additional considerations like debouncing and acceleration for gesture response might be needed to suit your particular game’s feel and responsiveness.

Keep on coding and experimenting! With each new technique you master, the closer you’ll get to bringing your game’s touch interaction to a whole new level.

As we progress, let’s delve into more practical applications of touch input in Godot 4. We’ll focus on long press detection, drag and drop interactions, advanced multi-touch handling, and creating a virtual joystick for character movement.

Long Press Detection

Long press is commonly used for showing context menus or initiating certain types of interactions. We’ll need to track the duration of a touch.

var touch_start_time = 0

func _input(event):
    if event is InputEventScreenTouch:
        if event.is_pressed():
            touch_start_time = OS.get_ticks_msec()
            var touch_duration = OS.get_ticks_msec() - touch_start_time
            if touch_duration > 500: # 500 milliseconds for long press
                print("Long press detected")

In this example, if the touch is held for longer than 500 milliseconds, it’s identified as a long press.

Drag and Drop

Drag and drop functionality allows players to interact with objects in a tactile way. Your game objects will need a collider and possibly a rigidbody for physics-based interactions.

var dragging = false
var drag_target = null

func _input(event):
    if event is InputEventScreenTouch:
        if event.is_pressed() and not dragging:
            var collider = get_collider_at_point(event.position)
            if collider:
                dragging = true
                drag_target = collider
        elif not event.is_pressed() and dragging:
            dragging = false
            drag_target = null

func get_collider_at_point(pos):
    var space_state = get_world_2d().direct_space_state
    var results = space_state.intersect_point(pos, 1)
    if results.empty():
        return null
    return results[0].collider

This snippet includes a helper function, get_collider_at_point, which uses Godot’s physics engine to find which object is under a given touch position. When dragging starts, drag_target is set and can be moved according to subsequent touch positions.

Advanced Multi-Touch

In complex games, you may want to handle multi-touch in a more nuanced way, where each finger could be interacting with different game elements.

var active_touches = {}

func _input(event):
    if event is InputEventScreenTouch:
        if event.is_pressed():
            active_touches[event.index] = event.position

func activate_game_element(touch_pos):
    # Logic for activating a game element

func deactivate_game_element(touch_pos):
    # Logic for deactivating a game element

Using a dictionary, we store active touches with their indices to track individual fingers, allowing for individual elements to be interacted with.

Virtual Joystick

A virtual joystick can be useful for directional input, particularly for character movement in mobile games.

var joystick_center = Vector2()
var is_joystick_active = false

func _input(event):
    if event is InputEventScreenTouch:
        if event.is_pressed() and not is_joystick_active:
            joystick_center = event.position
            is_joystick_active = true
        elif not event.is_pressed():
            is_joystick_active = false

func create_virtual_joystick(pos):
    # Instantiate the virtual joystick at pos

func remove_virtual_joystick():
    # Remove the joystick from the scene

This setup allows a joystick to appear where the user initially touches, providing an anchored control that disappears when released.

With these enhanced input functionalities, your games will not only feel more polished, but also provide the precise and fluid control that players expect. Remember to consider edge cases and include checks to prevent unexpected behavior when multiple inputs occur. Always aim for simplicity from the user’s perspective – even if the underlying code becomes more complex, the player’s experience should remain intuitive and straightforward.

Keep iterating on your touch input controls, test extensively, and listen to players’ feedback to fine-tune the responsiveness and feel of your game. With the right touch controls, you’re on your way to creating an engaging, successful mobile game in Godot 4.

Continue Your Godot Developer Journey

Your adventure into the world of game development with Godot doesn’t have to stop here. We at Zenva are committed to helping you expand your skills further. Whether you’re just starting off or ready to dig deeper into advanced topics, our Godot Game Development Mini-Degree is a comprehensive series of courses designed to teach you the ins and outs of creating games with Godot 4.

From crafting engaging 2D and 3D games to implementing gameplay control flow and mastering combat mechanics, this mini-degree has everything you need to take your game development skills to the next level. It’s a fantastic resource for becoming proficient in Godot 4 and for building a portfolio that showcases your ability to bring game concepts to life.

If you’re someone who prefers to have a range of options at your fingertips, explore our broader collection of Godot courses. This selection caters to every aspect of game development, providing you with the knowledge and tools needed to excel in the field. Think of it as your game development playground—where you can learn, experiment, and grow as a developer with the flexibility that suits your personal learning style.


Embarking on the journey of mastering Godot 4 with us at Zenva is more than just learning to code—it’s about bringing your gaming dreams to reality and joining a community of passionate developers. With the Godot Game Development Mini-Degree, every concept you learn and every line of code you write brings you one step closer to making a game that could captivate players around the world. Don’t hesitate to start; take the leap and build something great with your newfound skills in touch input and beyond!

We’re excited to see the amazing games you’ll create and are here to support you at every turn. Remember, your game development journey is unique, and with the right tools and guidance, the limits are truly as boundless as your imagination. So keep pushing forward, keep iterating, and keep learning with Zenva—your trusted ally in game development education. Let the world play your creations!

Python Blog Image

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