Search code examples
pythonpygamejoystick

Pygame.joystick returning 0s


I am attempting to build my own mini-library to simplify joystick use in pygame. However, when I attempt to read the buttons and axes, they all return 0, but only in the assign function (I am using a Logitech attack 3)

import sys

import pygame


joysticks = []

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


# Variables for locations in list #
AXIS_PITCH = 1
AXIS_ROLL = 0
AXIS_THROTTLE = 2
BUTTON_TRIGGER = BUTTON_1 = 3
BUTTON_2 = 4
BUTTON_3 = 5
BUTTON_4 = 6
BUTTON_5 = 7




# Must be called first, initializes joysticks #
def init():
    for joy in range(pygame.joystick.get_count()):
        joysticks.append(pygame.joystick.Joystick(joy))
        joysticks[joy].init()


# Needs player count, surface to draw to, font to use, colour of text, dimesions of screen #
def assign(players, screen, font, colour, dimensions):
#     unassigned = joysticks.copy()
    toReturn = []
    for i in range(players):
        assigned = False
        while(not assigned):
            if(pygame.key.get_pressed()[pygame.K_ESCAPE]): pygame.quit(); sys.exit();
            screen.fill([0,0,0])
            outString = "Player "+str(i+1)+" pull the trigger"
            out = font.render(outString, 1, colour, None)
            screen.blit(out, (dimensions[0]/2-out.get_width()/2, dimensions[1]/2-out.get_height()/2))
            pygame.display.flip()
            for stick in joysticks:
                print(stick.get_axis(1))
                if(stick.get_button(0) == 1):
                    print("Triggered")
                    if(stick not in toReturn):
                        toReturn.append(stick)
                        assigned = True
    return(toReturn)


# Returns the values of three axis, and 5 buttons on the passed joystick
def check(joystick):
    toReturn = []
    toReturn.append(joystick.get_axis(0))
    toReturn.append(joystick.get_axis(1))
    toReturn.append(joystick.get_axis(2))
    toReturn.append(joystick.get_button(0))
    toReturn.append(joystick.get_button(1))
    toReturn.append(joystick.get_button(2))
    toReturn.append(joystick.get_button(3))
    toReturn.append(joystick.get_button(4))
    return(toReturn)

If you need any more code, just ask. Thanks in advance!


Solution

  • Functions like get_pressed(), get_button(), get_axis() may not work if you don't process events - when you don't use pygame.event.get() or other event functions which call pygame.event.pump() to get information from system.

    Use pygame.event.get() (or other event functions) periodically (ie. in your while loop) to get current information from system.