InputMap in Godot – Complete Guide

Managing input in any game engine is crucial for creating interactive and responsive gameplay. Godot 4’s InputMap class takes this functionality a step further by offering developers a flexible system to manage input actions. This system isn’t just about detecting keystrokes or button presses; it gives you the power to define, reconfigure, and fine-tune how your game responds to a myriad of input devices, creating a seamless and intuitive experience for your players.

What is InputMap?

Understanding InputMap

InputMap is a core feature in Godot 4 that allows for the abstract mapping of inputs to actions. An action can be anything from jumping, shooting, or opening a menu. By using InputMap, you’re not hardcoding specific keys or buttons into your game. Instead, you’re assigning these keys to named actions. This makes it easier to change controls and support multiple input devices.

The Purpose of InputMap

Using InputMap has several practical benefits:

– Allows for customization of controls by the player.
– Makes it easier to add support for different input devices.
– Simplifies the process of detecting and responding to inputs within your game scripts.

Why Should I Learn InputMap?

Learning how to leverage InputMap in Godot 4 is essential because:

– It creates more accessible and user-friendly games.
– It future-proofs your game by making it easier to update and expand control schemes.
– It’s a fundamental skill that you will utilize in almost every interactive project you undertake with Godot.

By mastering the InputMap in Godot 4, you set the stage for creating dynamic and flexible games that stand out in the crowded field of indie games, opening up the path to designing more engaging and polished gameplay experiences.

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

Defining Actions and Assigning Inputs

To start using InputMap, you need to define actions and assign keys, mouse buttons, or joystick buttons to them. Let’s define an action for jumping.

InputMap.add_action("player_jump")
InputMap.action_add_event("player_jump", InputEventKey.new().set_scancode(KEY_SPACE))

This code creates a new action called “player_jump” and binds the spacebar key to it. But what if we want to support gamepad users? We can add a joystick button to the same action.

var gamepad_button = InputEventJoypadButton.new()
gamepad_button.button_index = JOY_BUTTON_0
InputMap.action_add_event("player_jump", gamepad_button)

Checking for Input in Code

Now that we have our actions defined, we can check if the action is being pressed in our game logic. Here’s how you can do it in a script attached to the player node.

func _process(delta):
    if Input.is_action_pressed("player_jump"):
        # Code to make the player jump

You might also want to handle the input only when it’s just been pressed, to avoid a continuous response while the button is held down.

func _process(delta):
    if Input.is_action_just_pressed("player_jump"):
        # Code to trigger a single jump

Supporting Multiple Keys for an Action

Not all players have the same preferences, and some might want to use a different key for jumping. Fortunately, InputMap lets us map multiple keys to the same action with ease.

InputMap.action_add_event("player_jump", InputEventKey.new().set_scancode(KEY_W))
InputMap.action_add_event("player_jump", InputEventKey.new().set_scancode(KEY_UP))

This allows the player to use either W, the up arrow key, or the spacebar to trigger the “player_jump” action.

Reconfiguring Controls at Runtime

A well-designed game allows players to reconfigure their controls. With InputMap, you can let the players change their keybinding.

func _set_new_key_for_action(action, new_key):
    # First, let's remove all the events associated with this action.
    InputMap.action_erase_events(action)
    
    # Now, assign the new key to the defined action.
    var input_event = InputEventKey.new()
    input_event.set_scancode(new_key)
    InputMap.action_add_event(action, input_event)

# Assuming the new key is stored in a variable called 'selected_key'.
_set_new_key_for_action("player_jump", selected_key)

In this snippet, `_set_new_key_for_action` is a function that receives an action name and a new key scancode to map.

This second part of our tutorial covers the basics of using the InputMap in Godot 4. We have defined actions, assigned keys, checked for input in our game code, supported multiple keys for single actions, and shown an example of how players can reconfigure controls. In the next part, we will dive deeper and look at how to manage and handle more complex input scenarios.

Handling Axis-based Inputs

Many games require analog input, such as a joystick axis for smooth movement or camera control. Godot’s InputMap can handle this as well. Here’s how we can map horizontal movement on a joystick.

var joy_axis = InputEventJoypadMotion.new()
joy_axis.axis = JOY_AXIS_0
joy_axis.axis_value = 1 # Right
InputMap.action_add_event("player_move_right", joy_axis)

joy_axis = InputEventJoypadMotion.new()
joy_axis.axis = JOY_AXIS_0
joy_axis.axis_value = -1 # Left
InputMap.action_add_event("player_move_left", joy_axis)

Now let’s check for this input within your player’s script.

func _process(delta):
    var axis_value = Input.get_action_strength("player_move_right") - Input.get_action_strength("player_move_left")
    if axis_value != 0:
        # Code to move the player right or left based on the axis_value

Combining Actions for Complex Inputs

Sometimes, you may want to check for a combination of inputs to trigger an action, like pressing SHIFT to run while moving. Here’s how you can manage this.

func _process(delta):
    var is_running = Input.is_action_pressed("player_run")
    var is_moving_right = Input.is_action_pressed("player_move_right")
    
    if is_moving_right and is_running:
        # Code for running right
    elif is_moving_right:
        # Code for walking right

Using Input Events for More Control

InputMap is also useful for responding to raw input events, which can provide more context about the input, like the pressure of a button press. Here’s how you handle an input event in the `_input` function.

func _input(event):
    if event is InputEventKey and event.pressed and event.scancode == KEY_SPACE:
        # Trigger jump with additional conditions

Creating Context-sensitive Controls

Games often need different controls depending on the current state, like when in a vehicle versus on foot. You can easily switch between different sets of inputs using InputMap.

func enter_vehicle_mode():
    InputMap.action_erase_events("player_jump")
    InputMap.action_add_event("player_jump", InputEventKey.new().set_scancode(KEY_ENTER))

func exit_vehicle_mode():
    InputMap.action_erase_events("player_jump")
    InputMap.action_add_event("player_jump", InputEventKey.new().set_scancode(KEY_SPACE))

Handling Touch Input

For mobile games, touch input is essential. Godot’s InputMap lets you define actions for touch events just like any button or key.

var touch_event = InputEventScreenTouch.new()
touch_event.index = 0 # First finger
InputMap.action_add_event("player_jump", touch_event)

To check if a touch event is occurring as an action:

func _process(delta):
    if Input.is_action_just_pressed("player_jump"):
        # Code for player to jump on touch

Debouncing Input

Sometimes, you might want to ensure an action is not triggered too frequently. This can be handled using a timer to debounce the input.

var can_jump = true

func _process(delta):
    if Input.is_action_just_pressed("player_jump") and can_jump:
        can_jump = false
        # Jump code here
        start_jump_cooldown()

func start_jump_cooldown():
    var timer = Timer.new()
    timer.wait_time = 1.0 # Cooldown in seconds
    timer.one_shot = true
    timer.connect("timeout", self, "_on_jump_cooldown_timeout")
    add_child(timer)
    timer.start()

func _on_jump_cooldown_timeout():
    can_jump = true

The above examples showcase the versatility and control Godot’s InputMap system offers. They provide a comprehensive understanding of how you can manipulate and respond to various types of input, ensuring that your game can cater to a wide range of players and play styles. This power at your fingertips is just one of the countless reasons why learning Godot 4’s InputMap feature opens up opportunities for innovation in your game development journey with us.Let’s explore more advanced features of Godot’s InputMap that can truly elevate your game’s input system. Remember, these techniques allow for nuanced control schemes that can be tailored to your game’s specific needs.

Implementing Action Strength and Deadzones

For analog inputs, like those from a joystick or trigger buttons, you might want to use the strength of the action (how much a joystick is tilted or a trigger is pressed). InputMap facilitates this with the `get_action_strength` method, along with the ability to set deadzones to ignore slight movements.

Here’s how to check the strength of an analog action and set a deadzone:

func _process(delta):
    var move_strength = Input.get_action_strength("player_move_right") - Input.get_action_strength("player_move_left")
    if abs(move_strength) > 0.2:  # Deadzone threshold
        # Apply movement with move_strength as a multiplier

Customizing Response to Combined Inputs

Combining actions can provide context-sensitive controls. Here’s an example where we want the player to dash if the jump and run buttons are pressed simultaneously:

func _process(delta):
    if Input.is_action_pressed("player_jump") and Input.is_action_pressed("player_run"):
        # Code for dash action

Detecting Double Taps

In certain games, double tapping a key might perform a special move. We can implement double tap detection using timers and input events.

First, set up a timer as a member variable. We’re using 0.3 seconds as our baseline for double tap speed.

var double_tap_timer = Timer.new()
var last_tap_time = 0.0

func _ready():
    double_tap_timer.wait_time = 0.3
    double_tap_timer.one_shot = true
    add_child(double_tap_timer)

Next, create a function to handle the input, where we’ll start the timer after the first tap and check for the second tap.

func _input(event):
    if event.is_action_pressed("player_move_right") and event.is_echo():
        if double_tap_timer.is_stopped():
            double_tap_timer.start()
        elif OS.get_ticks_msec() - last_tap_time < double_tap_timer.wait_time * 1000:
            # Double tap detected, perform dash move
            print("Dash Right!")

func _on_DoubleTapTimer_timeout():
    # Resets the timer for the next double tap detection
    last_tap_time = OS.get_ticks_msec()

Creating Custom Input Events

Sometimes you may need to create your own input events to integrate with external libraries or unusual hardware. Godot’s InputEvent class is extendable. Here, we create a custom input event for a hypothetical gesture control interface:

class_name GestureEvent extends InputEvent

var gesture_name = ""

func set_gesture(name):
    gesture_name = name

Now we can instantiate and parse this gesture as an action:

func parse_gesture_input(gesture_event):
    if gesture_event is GestureEvent:
        match gesture_event.gesture_name:
            "SwipeUp":
                Input.parse_input_event(InputEventAction.new().set_action("player_jump"))
            "SwipeDown":
                Input.parse_input_event(InputEventAction.new().set_action("player_crouch"))

Syncing InputMap With UI Elements

Finally, it can be very user-friendly to show updated control mappings in your game’s UI. Here’s how you can sync the InputMap with your game’s options menu or control settings screen. Assume ‘ui_action_label’ is a Label node that should display the key assigned to the “player_jump” action.

func update_ui_with_controls():
    for event in InputMap.get_action_list("player_jump"):
        if event is InputEventKey:
            var key_name = OS.get_scancode_string(event.scancode)
            ui_action_label.text = "Jump: %s" % key_name

Using these various techniques showcases the versatility of Godot’s InputMap and your game’s ability to handle a wide array of inputs. These approaches facilitate the creation of complex and dynamic control systems that are responsive to player preferences and input devices. These capabilities are critical for any modern game developer, and learning to implement them effectively will undoubtedly enhance your project’s interaction and engagement.

Where to Go Next in Your Godot Journey

Having explored the power of Godot 4’s InputMap, you’re likely eager to continue expanding your game development skills. We at Zenva encourage you to keep pushing the boundaries of what you can create. Whether you’ve just started your journey or you’re looking to refine your existing skills, our Godot Game Development Mini-Degree is an incredible next step.

The Mini-Degree is a curated series of courses that cover everything from foundational principles to advanced techniques in Godot. You’ll dive into various game genres, hone your scripting skills, and learn how to craft engaging gameplay experiences. At Zenva, you can go from beginner to professional, building a portfolio that showcases your ability to design and implement complete, polished games.

For a more expansive collection of courses that fit your specific needs and interests, explore our range of Godot courses. Each course is designed to equip you with practical, industry-relevant skills that will prepare you for a successful career in game development. Continue your learning journey with Zenva today and turn your game ideas into reality.

Conclusion

Mastering the InputMap system in Godot 4 can significantly enhance the quality and functionality of your games, offering players a seamless and intuitive experience. By embracing the skills we’ve shared, you’re not just improving your games—you’re expanding your creative toolbox and setting the foundation for a future-proof development process. Challenge yourself to implement these techniques in your next project and watch as your games come to life with responsive and customizable controls.

Whether you’re looking to take your first step or you’re ready for more complex projects, our Godot Game Development Mini-Degree provides the in-depth knowledge and practical experience you need to succeed. Don’t miss this opportunity to transform your passion for game development into a professional reality with Zenva.

FREE COURSES
Python Blog Image

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