Search code examples
pythonpygame

Pygame only recognizing one joystick in 2 joystick controller


I'm making code where I connect my bluetooth controller (PS4) and route it to certain commands with pygame, I want to use both joysticks but I apparently can only use one!

import pygame

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

# List the available joystick devices
for i in range(pygame.joystick.get_count()):
    print(f"Joystick {i}: {pygame.joystick.Joystick(i).get_name()}")

It gives me this:

Joystick 0: PS4 Controller

Why can't I use Joystick 1, and 0?


Solution

  • import pygame
    
    pygame.init()
    pygame.joystick.init()
    
    # List the available joystick devices
    joysticks = [pygame.joystick.Joystick(i) for i in range(pygame.joystick.get_count())]
    
    # Initialize all detected joysticks
    for joystick in joysticks:
        joystick.init()
        print(f"Joystick {joystick.get_id()}: {joystick.get_name()}")
    
    times = 0
    # Example: Print the position of the left and right analog sticks for all detected joysticks
    while True:
        pygame.event.get()
        for joystick in joysticks:
            left_x_axis = joystick.get_axis(0)
            left_y_axis = joystick.get_axis(1)
            right_x_axis = joystick.get_axis(2)
            right_y_axis = joystick.get_axis(3)
    
            print(f"Left Joystick: X={left_x_axis}, Y={left_y_axis}, Right Joystick: X={right_x_axis}, Y={right_y_axis}")
    

    I used a different method that works. Basically instead of asking to see if it exists, I made one variable equal 2 joysticks, making it so that I can split that variable into 2 joysticks.