InputEventShortcut in Godot – Complete Guide

Welcome to our tutorial on the InputEventShortcut class in Godot 4! Whether you’re new to the Godot Engine or you’ve been crafting games for a while, understanding input events is crucial for creating responsive and interactive experiences. In this comprehensive guide, we’ll delve into the intricacies of InputEventShortcut, a lesser-known but incredibly useful component in Godot’s event system. Get ready to learn how you can leverage this event to create more intuitive and polished games. By the end of this tutorial, you’ll gain valuable knowledge that can help bring your game’s controls to the next level.

What is InputEventShortcut?

InputEventShortcut is a special type of input event in Godot Engine that represents a triggered keyboard shortcut. It inherits from InputEvent, which is the base for all input event classes. This feature is particularly important when you want to implement customizable keyboard shortcuts or handle complex input combinations without writing a lot of boilerplate code.

What is it for?

The primary use of InputEventShortcut is to receive input events that are not directly tied to a single keypress but rather to a combination of keys or a predefined action. In Godot, this is often utilized within the editor itself for actions initiated through the Command Palette. However, developers can send these events manually using the Viewport’s push_input method, offering flexibility in handling user inputs.

Why Should I Learn It?

Learning about InputEventShortcut is important for a few reasons:
– It simplifies the input handling logic by abstracting complex key combinations.
– It enhances the user experience by supporting intuitive shortcuts.
– It makes your game more customizable and accessible since you can allow players to define their own shortcut keys.
By understanding InputEventShortcut, you’ll be adding a professional touch to your Godot projects by enabling more sophisticated control schemes.

Stay tuned as we dive into code examples and practical uses for InputEventShortcut in the following sections.

CTA Small Image
FREE COURSES AT ZENVA
LEARN GAME DEVELOPMENT, PYTHON AND MORE
ACCESS FOR FREE
AVAILABLE FOR A LIMITED TIME ONLY

Creating and Emitting InputEventShortcut Instances

Before we can handle InputEventShortcut instances, we need to create and emit them. To define a shortcut event, we will use the built-in method in Godot, `InputEventKey`. First, let’s create a simple input event for a shortcut, which in our example will be the combination `Ctrl + S`, commonly used for saving:

var event = InputEventKey.new()
event.set_control(true)
event.set_keycode(KEY_S)
var shortcut = InputEventShortcut.new()
shortcut.set_shortcut(event)

Now that we have our InputEventShortcut created, we can emit it manually. This is especially useful for testing your input handling when building editor plugins or custom UI elements:

get_tree().viewport.push_input(shortcut)

These lines of code are the foundation of creating and using keyboard shortcuts. Let’s move on to handling these events in our game.

Handling InputEventShortcut in Scripts

Now that we know how to create InputEventShortcut instances, the next step is to handle them. We use the `_input` function to react to InputEvents, including our custom shortcuts. Here’s a basic example:

func _input(event):
    if event is InputEventShortcut and event.is_valid():
        var input_event = event.get_shortcut()
        if input_event.as_text() == "Ctrl+S":
            save_game()

In this script, when the player presses `Ctrl + S`, the `save_game()` function is called. This is a simple way to check for our shortcut. We can make this more robust by checking for just the Ctrl key and the S key separately, as follows:

func _input(event):
    if event.is_action_pressed("ui_save"):
        save_game()

We can configure the “ui_save” action in Godot’s Input Map with the `Ctrl + S` key combination to make our code cleaner and the shortcuts easily customizable.

Mapping Shortcuts to Actions

By mapping our shortcuts to actions in Godot’s Input Map, we can easily make our controls user-configurable. This allows players to change their key bindings if they wish. Here’s how you can set up a new action and associate it with a shortcut:

1. Go to **Project** > **Project Settings** > **Input Map**.
2. Add a new action named `ui_save`, for example.
3. Click “Add Event” and choose “Key” to attach a keyboard key. Set it to `Ctrl + S`.

In script, you will then check for this action:

func _input(event):
    if event.is_action_pressed("ui_save"):
        save_game()

The benefit here is significant: our `_input` function becomes more readable, and we keep key mappings contained within the Godot editor, making them easy to modify later on if needed.

Improving User Experience with Descriptive Shortcuts

For a better user experience, especially if your game has a complex control scheme, you may want to provide descriptions for your shortcuts. You can do this by extending the InputEventShortcut class:

class_name DescriptiveShortcut extends InputEventShortcut

var description: String = ""

func _init(event, desc : String):
    self.set_shortcut(event)
    self.description = desc

Then, when creating your shortcut, you add a description too:

var event = InputEventKey.new()
event.set_control(true)
event.set_keycode(KEY_S)
var shortcut = DescriptiveShortcut.new(event, "Save the game")

# Now when processing the event:
func _input(event):
    if event is DescriptiveShortcut:
        print(event.description)
        if event.get_shortcut().as_text() == "Ctrl+S":
            save_game()

This approach helps provide context for each shortcut, which can be displayed in a controls menu or a help screen within your game. In the next section, we will explore more ways to utilize InputEventShortcut to make our game controls even more dynamic.

Contextual Shortcut Handling

There may be cases where the same shortcut performs different actions depending on the context. For instance, `Ctrl + Z` might undo text in a text box or a movement action during gameplay. You can handle this smoothly by checking the state of the game.

func _input(event):
    if event is InputEventShortcut:
        if in_text_edit and event.get_shortcut().as_text() == "Ctrl+Z":
            undo_text_edit_function()
        elif in_gameplay and event.get_shortcut().as_text() == "Ctrl+Z":
            undo_gameplay_action()

It’s important to ensure that we effectively manage our input context to avoid unexpected behavior or conflicts between controls.

Utilizing InputEventShortcut in Custom Menus

Shortcuts are often used in menus to make navigation easier. By using InputEventShortcut, you can enable quick access to various parts of your menu. For instance, pressing `Ctrl + O` to open a file dialog from the main menu.

func _input(event):
    if event is InputEventShortcut and event.get_shortcut().as_text() == "Ctrl+O":
        open_file_dialog()

You can bind the open_file_dialog function directly to a button in the menu as well as to the shortcut, providing different methods of interaction for the user.

Defining Global Shortcuts

Some shortcuts are expected to work no matter what part of the game is currently active. Setting up a global shortcut listener is simple:

func _ready():
    set_process_input(true)

func _input(event):
    if event is InputEventShortcut and event.get_shortcut().as_text() == "Ctrl+M":
        toggle_music()

On the other hand, you can have global shortcuts tied to an autoloaded script. An autoloaded script has a global scope and loads when the game starts, perfect for managing inputs universally.

class_name GlobalShortcutManager

func _input(event):
    if event is InputEventShortcut:
        match event.get_shortcut().as_text():
            "Ctrl+M":
                toggle_music()
            "Ctrl+H":
                display_help_screen()

Customizing Shortcut Responses

Sometimes, you might want to enable or disable shortcuts dynamically. Godot allows us to enable or disable the actions associated with shortcuts, offering fine-tuned control over their availability.

func disable_shortcuts():
    InputMap.action_set_enabled("ui_save", false)

func enable_shortcuts():
    InputMap.action_set_enabled("ui_save", true)

In this example, you can toggle the `ui_save` action, effectively enabling or disabling the shortcut linked to it. This is incredibly useful during gameplay or cutscenes where you don’t want the player to trigger certain actions.

Rebinding Shortcuts In-Game

To enhance the game experience, you might want to allow players to rebind their shortcuts. Here’s an example of how to rebind an action in-game:

func rebind_shortcut(old_event, new_event):
    var action = InputMap.get_action_from_event(old_event)
    if action != "":
        InputMap.action_erase_event(action, old_event)
        InputMap.action_add_event(action, new_event)

By utilizing `get_action_from_event`, you can find the action currently assigned to a given event and update it with `action_add_event` to the new event the player has chosen. This provides complete control over input configuration.

As we’ve learned, InputEventShortcut is a powerful tool in the Godot Engine, making game controls intuitive, responsive, and customizable. Whether you’re new to Godot or a seasoned pro, mastering InputEventShortcut will undoubtedly increase the quality of interaction in your game projects. With this guide, we at Zenva hope to have provided you with a solid understanding and practical skill set to improve your game development journey. Happy coding!

Implementing Multi-Language Keyboard Support

To accommodate players from different regions, your game must handle various keyboard layouts. Here’s how to account for different key positions based on the layout:

func _input(event):
    if event is InputEventKey and event.pressed:
        # Check for the physical key, not the key symbol, for layout independence
        if event.physical_keycode == KEY_Q:
            perform_quick_action()

In this case, the `physical_keycode` property ensures that you’re checking the physical position of the key, which helps avoid confusion for users with non-QWERTY keyboard layouts.

Enabling Cheat Codes through Shortcuts

Shortcuts can be a fun way to implement cheat codes. Here’s how you could program a sequence of shortcuts to activate a cheat:

var cheat_code = [KEY_UP, KEY_UP, KEY_DOWN, KEY_DOWN, KEY_LEFT, KEY_RIGHT, KEY_LEFT, KEY_RIGHT, KEY_B, KEY_A]
var current_index = 0

func _input(event):
    if event is InputEventKey and event.pressed:
        if event.scancode == cheat_code[current_index]:
            current_index += 1
            if current_index == cheat_code.size():
                activate_cheat_code()
                current_index = 0
        else:
            current_index = 0

Listening for a sequence in `_input` allows us to match the input to an array of keycodes representing the cheat code.

Capturing Text Input Alongside Shortcuts

There are times when you need to capture text input while not interrupting other shortcuts. Here’s an example:

func _input(event):
    if event is InputEventKey and event.echo == false:
        # Handle text input in a text box
        if event.pressed and event.unicode != 0:
            my_text_box += char(event.unicode)
        # Handle a shortcut (not a text input)
        elif event.is_action_pressed("ui_fullscreen"):
            toggle_fullscreen()

We check that the event is not an echo — key repeats that occur when a key is held down which we usually don’t want for text input — and use the `unicode` property for capturing printable characters.

Combining Keyboard and Mouse Inputs

Combining keyboard events with other input types, like mouse clicks, can create more complex interactions. For example, you might want to increase an object’s size only if the `Ctrl` key is held while the mouse is clicked:

func _input(event):
    if event is InputEventMouseButton and event.pressed:
        if Input.is_key_pressed(KEY_CONTROL):
            if event.button_index == BUTTON_LEFT:
                increase_object_size()

With `Input.is_key_pressed()`, we can check the state of a key at any time, not just when a specific event occurs.

Creating Undo and Redo Stack with Shortcuts

For games or applications that require an undo/redo functionality, you can implement this feature with shortcuts:

var undo_stack = []
var redo_stack = []

func _input(event):
    if event is InputEventShortcut:
        if event.get_shortcut().as_text() == "Ctrl+Z":
            undo_action()
        elif event.get_shortcut().as_text() == "Ctrl+Y":
            redo_action()

func undo_action():
    if undo_stack.size() > 0:
        var action = undo_stack.pop_back()
        # Execute the undo operation ...
        redo_stack.append(action)

func redo_action():
    if redo_stack.size() > 0:
        var action = redo_stack.pop_back()
        # Execute the redo operation ...
        undo_stack.append(action)

Each time an action that can be undone or redone is performed, it’s pushed to the respective stack. The `undo_action` and `redo_action` functions handle the logic for actually retracing the player’s steps.

Switching Control Schemes with Shortcuts

For games that feature multiple control schemes, use shortcuts to switch between them, enhancing the player’s experience:

enum ControlSchemes { SCHEME_KEYBOARD_MOUSE, SCHEME_CONTROLLER }

var current_scheme = ControlSchemes.SCHEME_KEYBOARD_MOUSE

func _input(event):
    if event is InputEventShortcut:
        if event.get_shortcut().as_text() == "Ctrl+K":
            switch_to_scheme(ControlSchemes.SCHEME_KEYBOARD_MOUSE)
        elif event.get_shortcut().as_text() == "Ctrl+C":
            switch_to_scheme(ControlSchemes.SCHEME_CONTROLLER)

func switch_to_scheme(scheme):
    current_scheme = scheme
    # Logic to adjust controls...

Whenever a scheme is activated, you adjust the game’s input logic according to the selected scheme. This offers a smooth transition for players who wish to alternate between different control devices or setups.

By incorporating these techniques into your Godot games, you provide robust, versatile, and user-friendly interactions. From supporting multiple keyboard layouts to crafting intricate control schemes, understanding InputEventShortcuts and handling input effectively are key to creating a memorable player experience. Remember, these snippets are just the beginning of what’s possible with Godot’s flexible input management system, so feel free to get creative and adapt these examples to fit your specific game development needs!

Continue Your Game Development Journey

If you’ve enjoyed learning about InputEventShortcut and are excited to further expand your Godot development skills, we invite you to keep this momentum going with our Godot Game Development Mini-Degree. This collection of courses is meticulously crafted to guide you through the essentials of building cross-platform games with Godot 4. You’ll explore a wide variety of game genres and mechanics as you learn how to create immersive 2D and 3D experiences.

Learning continues beyond this topic. We encourage you to dive deep into our curriculum that takes you from the foundational principles of game creation to mastering advanced features of the Godot engine. You’ll gain practical, project-based experience that can serve as a springboard for both personal and professional projects.

In addition, to explore a broader range of courses and perhaps find specific answers to challenges you encounter, be sure to peruse our complete array of Godot courses. At Zenva, we’re committed to providing high-quality content that helps you transition from beginner to pro at your own pace, on any device, at any time. So whether you’ve just started your path in game development or looking to level up your skills, Zenva has the resources to support your learning adventure!

Conclusion

In exploring the dynamic world of InputEventShortcut, we’ve seen just how much depth and flexibility Godot offers for customizing user input. From creating personalized control schemes to implementing global shortcuts, the possibilities to enhance gameplay and streamline player interaction are boundless. We hope this tutorial ignites your imagination and shows you the potential to craft truly engaging and player-friendly game experiences.

As you continue honing your skills, remember that your journey doesn’t stop here. Dive deeper into game development with our Godot Game Development Mini-Degree and unlock a treasure trove of knowledge that awaits you. At Zenva, we’re proud to be part of your learning path, offering the tools and courses to shape your dreams into reality. So what are you waiting for? Take the next step and let’s build something amazing together!

FREE COURSES
Python Blog Image

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