Gamepad and joystick input in Pygame
Supporting controllers makes many games feel better. Learn to detect pads as they connect, read sticks with a dead zone, buttons and the D-pad, and keep keyboard controls working too.
On this page
The joystick module#
pygame.init() starts the joystick module. Each connected device is a pygame.joystick.Joystick object offering:
| Method | Returns |
|---|---|
get_name() | The device's name, such as a controller model |
get_numaxes(), get_axis(i) | Analog inputs (sticks, triggers) from -1.0 to 1.0 |
get_numbuttons(), get_button(i) | Buttons, True while held |
get_numhats(), get_hat(i) | D-pads as (x, y) with values -1, 0 or 1 |
get_instance_id() | An ID that matches the instance_id in joystick events |
rumble(low, high, duration_ms) | Vibration, if the device supports it |
Detect controllers as they connect#
Players plug in pads after the game starts, and unplug them mid-game. Pygame sends JOYDEVICEADDED for each pad, including ones connected at start-up, and JOYDEVICEREMOVED when one disappears. Create Joystick objects in response:
"""Gamepad input: hot-plugging, axes with a dead zone, buttons and the D-pad (hat)."""
import pygame
DEADZONE = 0.2
pygame.init()
screen = pygame.display.set_mode((640, 360))
clock = pygame.time.Clock()
font = pygame.font.Font(None, 26)
joysticks = {} # instance_id -> Joystick
pos = pygame.Vector2(320, 180)
running = True
while running:
dt = clock.tick(60) / 1000
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.JOYDEVICEADDED: # also sent for pads connected at start-up
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")
elif event.type == pygame.JOYBUTTONDOWN:
print("Button", event.button, "on pad", event.instance_id)
move = pygame.Vector2()
for joy in joysticks.values():
x, y = joy.get_axis(0), joy.get_axis(1) # left stick on most pads
if abs(x) > DEADZONE:
move.x += x
if abs(y) > DEADZONE:
move.y += y
if joy.get_numhats():
hx, hy = joy.get_hat(0) # D-pad: y is +1 for up
move += (hx, -hy)
keys = pygame.key.get_pressed() # keyboard fallback
move += (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT], keys[pygame.K_DOWN] - keys[pygame.K_UP])
if move.length_squared() > 1:
move.scale_to_length(1)
pos += move * 260 * dt
pos.x = max(20, min(620, pos.x))
pos.y = max(20, min(340, pos.y))
screen.fill((20, 26, 46))
pygame.draw.circle(screen, (244, 197, 49), pos, 18)
status = ", ".join(j.get_name() for j in joysticks.values()) or "No gamepad connected (arrow keys work too)"
screen.blit(font.render(status, True, (230, 236, 247)), (16, 16))
pygame.display.flip()
pygame.quit()The program works without a controller too: arrow keys move the circle, and the status line says no gamepad is connected.
Dead zones#
Analog sticks rarely rest exactly at 0; they report small values such as 0.03 when untouched, which makes characters drift. Ignore values below a dead zone of around 0.15–0.25. For smoother control, rescale the remaining range so movement starts gently just outside the dead zone.
Buttons and events#
Use JOYBUTTONDOWN events for one-off actions (jump, confirm, pause) and get_button() or get_axis() each frame for continuous ones, exactly like keyboard events versus key state. D-pads send JOYHATMOTION events and report (0, 1) for up. Note that y is positive up for hats but positive down for sticks and the screen.
Mapping differences#
Button and axis numbers vary between controller models and operating systems: "button 0" isn't the same physical button everywhere. Good practice:
- Provide a controls screen that lets players press the button they want for each action.
- Store mappings per controller name.
- Always keep keyboard controls as a fallback.
Menus#
Let the D-pad and left stick move the menu selection and button 0 confirm. If your menu class already supports arrow keys and Enter (as in menus and game states), translate gamepad events into the same actions.
Rumble#
if joy.rumble(0.4, 0.8, 300): # low- and high-frequency strength (0-1), duration in ms
pass # returns False if the device can't rumbleUse vibration sparingly and offer a setting to turn it off.