pythonpygamedisplayjoystick

Pygame not returning joystick axis movement without display


I've seen other solutions to this problem say that you either need to call the pygame.event.pump() or initialize the joystick outside of the while loop. However, even with these solutions, I'm getting 0's for the joystick axes values.

If I uncomment just the pygame.display.set_mode((1, 1)), then the code works as expected, and the values are output to the console.

Is there a way to still get the axes values without having to create the extra window?

Also, I am running python 3.6 on Windows 10.

import pygame

FRAMES_PER_SECOND = 20

pygame.init()
pygame.joystick.init()

# pygame.display.set_mode((1,1))

# Used to manage how fast the screen updates.
clock = pygame.time.Clock()

xboxController = pygame.joystick.Joystick(0)
xboxController.init()


# Loop until the user presses menu button
done = False

print('Found controller\nStarting loop...')
while not done:
    pygame.event.pump()
    for event in pygame.event.get():
        if event.type == pygame.JOYBUTTONDOWN and event.button == 7:
            print(f'Exiting controller loop')
            done = True

    for i in range(xboxController.get_numaxes()):
        print(f'Axis {i}: {xboxController.get_axis(i)}')

    # pygame.display.flip()

    clock.tick(FRAMES_PER_SECOND)

Output:

pygame 1.9.6
Hello from the pygame community. https://www.pygame.org/contribute.html
Found controller
Starting loop...
Axis 0: 0.0
Axis 1: 0.0
Axis 2: 0.0
Axis 3: 0.0
Axis 4: 0.0
.
.
.

Solution

  • I would probably move away from Pygame unless you need the whole underlaying GL features, as the library is meant for 2D/3D game development. Although it might be possible to use it for these purposes, issues down the line is more or less unavoidable. A perhaps simpler approach would be to go with python's input library, which can handle gamepads (joysticks).

    from inputs import get_gamepad
    
    while True:
        events = get_gamepad()
        for event in events:
            if event.ev_type == 'Absolute':
                if event.code == 'ABS_X':
                    print(f'Left joystick x: {event.state}')
                elif event.code == 'ABS_Y':
                    print(f'Left joystick y: {event.state}')
                elif event.code == 'ABS_RX':
                    print(f'Right joystick x: {event.state}')
                elif event.code == 'ABS_RY':
                    print(f'Right joystick y: {event.state}')