Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 41 ยท Sound and Input

Gamepad and Touch Input in Pygame

Add controller support to Pygame: detect joysticks, read axes and buttons, handle dead zones and hot-plugging, and unify keyboard, gamepad and touch input.

Many players would rather use a controller than a keyboard, and phones and tablets add touch to the mix. Pygame covers all of these through the pygame.joystick module (which includes gamepads) and through touch events that the operating system sends as FINGERDOWN, FINGERMOTION and FINGERUP.

You will learn how to detect controllers, read sticks and buttons, remove stick drift with a dead zone, survive unplugging, and funnel every input device into the same game actions. The Pygame code is read-only here; the stand-ins let you test the math that makes controllers feel right.

Finding and opening a joystick

In Pygame 2 a controller must be opened as a Joystick object before it sends events. The device index belongs to the connection, so the safest approach is to listen for the add and remove events.

Python
import pygame
pygame.init()

joysticks = {}          # instance_id -> Joystick

for event in pygame.event.get():
    if event.type == pygame.JOYDEVICEADDED:
        joy = pygame.joystick.Joystick(event.device_index)
        joysticks[joy.get_instance_id()] = joy
        print("connected:", joy.get_name())
    elif event.type == pygame.JOYDEVICEREMOVED:
        joysticks.pop(event.instance_id, None)
        print("disconnected")

At startup, Pygame 2 generates a JOYDEVICEADDED event for each controller that is already plugged in, so you do not need a separate scan. Holding the objects in a dictionary keeps them alive. If the object is garbage collected the controller stops reporting.

Axes, buttons and hats

A typical gamepad exposes:

  • Axes: continuous values from -1.0 to 1.0. Two for the left stick (0 = horizontal, 1 = vertical, with down positive), two for the right stick, and two triggers that go from -1.0 (released) to 1.0 (fully pressed) on many controllers.
  • Buttons: on or off (A, B, X, Y, bumpers, start...).
  • Hats: the directional pad, reported as (x, y) with each being -1, 0 or 1.
Python
joy = joysticks[0]                       # example
x = joy.get_axis(0)                      # left stick horizontal
y = joy.get_axis(1)                      # left stick vertical
jump_down = joy.get_button(0)            # usually A on Xbox-style pads
dpad_x, dpad_y = joy.get_hat(0)

Events exist too: JOYAXISMOTION, JOYBUTTONDOWN, JOYBUTTONUP and JOYHATMOTION. Use JOYBUTTONDOWN for one-shot actions (jump), and polling get_axis for movement, the same split you saw in keyboard and mouse input.

Button numbering depends on the controller and operating system. Never hard-code numbers without letting players remap them, and print joy.get_name() into a log for support requests.

Dead zones

Real sticks never rest at exactly 0.0. A worn stick might report 0.07 while untouched, and your character would slowly drift. The cure is a dead zone: ignore small values and rescale the rest so movement still starts smoothly at 0.

Python A dead zone function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Without the rescale step, a stick pushed just beyond the zone would jump from 0 to 0.15 speed instantly. With it, the output climbs smoothly from 0.

For two-dimensional sticks a radial dead zone is better than treating each axis separately, since a stick pushed diagonally moves on a circle:

Python
import pygame

def stick_vector(joy, zone=0.2):
    v = pygame.Vector2(joy.get_axis(0), joy.get_axis(1))
    if v.length() < zone:
        return pygame.Vector2()
    if v.length() > 1:
        v.scale_to_length(1)
    return v

Try it: one action layer for every device

The best way to support many devices is to stop asking "was the A button pressed?" in game code. Instead, each device is translated into the same small set of actions, and the game only knows about actions. This stand-in simulates three devices feeding the same player.

Python Keyboard, gamepad and touch as one input

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Adding a new device later means writing one more from_xxx function, and nothing in the movement or jumping code changes.

Touch input

On touch screens SDL sends finger events with coordinates normalized to the range 0.0 to 1.0, not pixels:

Python
if event.type == pygame.FINGERDOWN:
    px = event.x * screen_width
    py = event.y * screen_height
    if jump_button_rect.collidepoint(px, py):
        player.jump()

For simple games it is easier to rely on the fact that, on many platforms, SDL also emulates a left mouse click for the first finger. If your mouse code uses MOUSEBUTTONDOWN and collidepoint, it often works on touch screens with no extra code. Use real finger events when you need multi-touch (two thumbs on virtual buttons) or gestures.

Design touch controls to be big: buttons at least 60 to 80 pixels wide, placed at the screen edges where thumbs rest.

Rumble

Some controllers vibrate. joy.rumble(low_frequency, high_frequency, duration_ms) takes strengths from 0.0 to 1.0 and returns whether the controller accepted it. Use it sparingly for hits and explosions, and offer an option to turn it off.

Python
if joy.rumble(0.4, 0.9, 200):
    pass   # vibrating for 200 ms

Common mistakes

  • Forgetting to keep the Joystick object. Store it in a list or dictionary.
  • Assuming button 0 is "A". Provide remapping.
  • No dead zone. The character drifts on its own.
  • Not handling unplugging. Always handle JOYDEVICEREMOVED and pause the game, since the player may have lost their only controller.
  • Reading axes in JOYAXISMOTION only. Axis events fire only on change, so a held stick sends nothing new. Poll get_axis once per frame instead.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does a game apply a dead zone to joystick axes?

    Worn or cheap sticks rest slightly away from 0.0. A dead zone removes that drift.
  2. 2. Which event tells you a controller was plugged in while the game runs?

    JOYDEVICEADDED carries a device_index you pass to pygame.joystick.Joystick.
  3. 3. What range do touch coordinates in FINGERDOWN events use?

    They are normalized, so multiply by the window size to get pixels.
  4. 4. What is the main benefit of translating devices into actions?

    Game code asks for 'jump' or 'move_x' and never needs to know which device produced them.

Summary

  • Open each controller as a Joystick when JOYDEVICEADDED arrives, and keep the object referenced.
  • Axes are floats from -1 to 1, buttons are booleans and hats are (x, y) pairs.
  • Apply a (preferably radial) dead zone and rescale the remainder.
  • Translate keyboard, gamepad and touch into shared actions so the game stays device-agnostic.
  • Touch events use normalized coordinates; large on-screen buttons work best.

Next: Buttons and Text Input Boxes