All articles

Godot InputMap and gamepads: actions, axes and device switching

Defining actions in code, PhysicalKeycode, GetVector and deadzones, positional JoyButton values, switching between keyboard and gamepad, _UnhandledInput and testing with synthetic input.

t.Turgay
Godot InputMap and gamepads: actions, axes and device switching

In Godot, game code asks about actions rather than keys. InputMap binds an action name such as move_left to one or more input events, so keyboard, mouse and gamepad can drive the same action. That separation lets rebinding, gamepad support and platform-specific layouts change without touching game rules. The examples below are independent fragments written against the Godot 4 C# API.

Building actions in code

Actions can also be defined in project.godot, but building them in code is easier to audit when user rebinding and platform differences exist. InputMap.HasAction checks for an action, AddAction creates it with its deadzone, ActionEraseEvents clears old bindings and ActionAddEvent adds a new event. One setup function then rebuilds the whole map from defaults plus user overrides each time it runs.

For key events, Keycode describes the logical key and PhysicalKeycode the physical position on the keyboard. Position-based movement keys such as WASD keep the same layout across keyboard layouts when bound by physical code. Shortcut labels should be produced from the action identifier, not from translated text, or the binding breaks when the language changes.

using Godot;

public static class Bindings
{
    public static void Bind(string action, params InputEvent[] events)
    {
        if (!InputMap.HasAction(action)) InputMap.AddAction(action, 0.25f); // explicit deadzone
        InputMap.ActionEraseEvents(action);
        foreach (var e in events) InputMap.ActionAddEvent(action, e);
    }

    public static void ApplyDefaults()
    {
        Bind("move_left",
            new InputEventKey { PhysicalKeycode = Key.A },
            new InputEventJoypadMotion { Axis = JoyAxis.LeftX, AxisValue = -1f });
        Bind("move_right",
            new InputEventKey { PhysicalKeycode = Key.D },
            new InputEventJoypadMotion { Axis = JoyAxis.LeftX, AxisValue = 1f });
        Bind("confirm",
            new InputEventMouseButton { ButtonIndex = MouseButton.Left },
            new InputEventJoypadButton { ButtonIndex = JoyButton.A });
    }
}

Godot — InputMap

Analog axes, GetVector and deadzones

A stick binds to an action with an axis and a sign: on the left stick X axis, a negative value means left and a positive value means right. The deadzone keeps small resting deviations of the stick from triggering the action. The second parameter of AddAction is that threshold; setting it explicitly makes behaviour more predictable across devices.

Input.GetVector turns four actions into one two-dimensional direction. The result uses a circular deadzone and its length never exceeds 1, so diagonal movement is not faster by accident. Use GetActionStrength when analog intensity matters and IsActionPressed when only the pressed state matters.

// Inside a CharacterBody2D script; MaxSpeed and Interact are illustrative.
public override void _PhysicsProcess(double delta)
{
    // Keyboard keys and the left stick drive the same four actions.
    Vector2 direction = Input.GetVector("move_left", "move_right", "move_up", "move_down");
    float boost = Input.GetActionStrength("boost");      // 0..1 from a trigger, 1 from a key
    Velocity = direction * MaxSpeed * (1f + boost);
    MoveAndSlide();

    if (Input.IsActionJustPressed("confirm")) Interact();
}

JoyButton positions and button labels

Godot's gamepad constants follow the SDL layout and are positional. JoyButton.A is the bottom face button: it is labelled A on an Xbox controller, Cross on PlayStation and B on a Nintendo controller. Whatever position confirm and back are bound to, the button name shown on screen must match the label on the controller in use.

Confirm and back may swap positions when the platform layout changes. Resolve that difference in one place in the action map; game code still asks for confirm and cancel. For UI focus navigation, use Godot's built-in ui_accept, ui_cancel and direction actions, and give Control nodes an explicit initial focus with FocusMode and GrabFocus.

Godot — Controllers, gamepads and joysticks

Switching the UI to the last used device

Automatic switching between keyboard/mouse and gamepad tracks the type of the last meaningful event. A key or mouse event selects the keyboard layout; a gamepad button or an axis movement above a threshold selects the gamepad layout. The threshold matters: a slightly drifting stick should not keep flipping the screen of a player who is using the mouse.

The Input.JoyConnectionChanged signal reports connected and disconnected devices. When the last used gamepad is removed and no other gamepad is connected, the UI can return to mouse mode. An event's Device field tells which controller produced it; vibration or player assignment can use that identifier. Device tracking must see every event, so it runs in _Input and does not consume anything.

public enum InputKind { KeyboardMouse, Gamepad }

public partial class DeviceTracker : Node
{
    public static InputKind Active { get; private set; } = InputKind.KeyboardMouse;
    private long _lastPad = -1;

    public override void _Ready() =>
        Input.Singleton.JoyConnectionChanged += OnJoyConnectionChanged;

    public override void _ExitTree() =>
        Input.Singleton.JoyConnectionChanged -= OnJoyConnectionChanged;

    public override void _Input(InputEvent e)
    {
        switch (e)
        {
            case InputEventKey or InputEventMouseButton or InputEventMouseMotion:
                Active = InputKind.KeyboardMouse;
                break;
            case InputEventJoypadButton:
            case InputEventJoypadMotion { AxisValue: > 0.5f or < -0.5f }:
                Active = InputKind.Gamepad;
                _lastPad = e.Device;
                break;
        }
    }

    private void OnJoyConnectionChanged(long device, bool connected)
    {
        if (!connected && device == _lastPad && Input.GetConnectedJoypads().Count == 0)
            Active = InputKind.KeyboardMouse;
    }
}

The order of _Input, GUI and _UnhandledInput

An event first reaches the nodes' _Input methods, then UI Control nodes, then the shortcut and unhandled input stages. Handling world actions such as clicking the map in _UnhandledInput keeps a click on a panel from leaking into the game. A node that consumes the event calls GetViewport().SetInputAsHandled() to stop later stages.

This split stops the same button from triggering two behaviours when it means confirm in a menu and an order in the game. If an open window consumes the input, the game world never sees that event in that frame, and no extra flag is needed when the window closes.

Godot — Using InputEvent

Vibration, synthetic input and map snapshots

Input.StartJoyVibration takes weak and strong motor magnitudes and a duration. Scale feedback to the importance of the event and let players disable it in settings. Input.ParseInputEvent feeds an event created in code as if it were real input; sending a virtual stick movement or button press in automated tests exercises the flow even on a machine with no gamepad.

The action map can be dumped to text and compared with an approved file: write the action name and a canonical description of each event, one per line. If a platform-specific change silently alters desktop bindings, the comparison fails during testing.

Godot — Input

Related technical articles

You have reached the end of this orbit.
Explore more articles
turgay.A little code, a few pixels, a lot of curiosity.© 2026 · Made on Earth