how to make sprite move upwards and downwards with joystick in pygame

First ensure that you have a joystick, by getting the number of joysticks by pygame.joystick.get_count(). Initialize the joystick by pygame.joystick.Joystick.init:

joystick = None
if pygame.joystick.get_count() > 0:
    joystick = pygame.joystick.Joystick(0)
    joystick.init()

Once a joystick is initialized, ist axis value can be get by pygame.joystick.Joystick.get_axis. The value returned by this function is in range [-1, 1]. -1 for the maximum negative tilt and +1 for the maximum positive tilt.
Note, each analog stick of a gamepad or joystick has 2 axis, one for the horizontal direction and 1 for the vertical direction. Since the amount of the value returned by get_axis() depends on the tilting of the analog stick you should multiply the speed by the value.
Further you should ignore values near 0 for the dead center, because of the inaccuracy of the hardware. This can be don by a simple check using the built in function abs(x) e.g. abs(axisval) > 0.1:

if joystick:
    axis_x, axis_y = (joystick.get_axis(0), joystick.get_axis(1))
    if abs(axis_x) > 0.1:
        player_one.speed_x = 5 * axis_x
    if abs(axis_y) > 0.1:
        player_one.speed_y = 5 * axis_y

See the following simple demo app:

import pygame
pygame.init()

size = (800,600)
screen = pygame.display.set_mode(size)
clock = pygame.time.Clock()
pos = [size[0]/2, size[1]/2]
speed = 5
joystick = None

done = False
while not done:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
        elif event.type == pygame.KEYDOWN:
            if event.key==pygame.K_RETURN:
                done = True

    if joystick:
        axis_x, axis_y = (joystick.get_axis(0), joystick.get_axis(1))
        if abs(axis_x) > 0.1:
            pos[0] += speed * axis_x
        if abs(axis_y) > 0.1:
            pos[1] += speed * axis_y
    else:
        if pygame.joystick.get_count() > 0:
            joystick = pygame.joystick.Joystick(0)
            joystick.init()
            print("joystick initialized")

    screen.fill((0, 0, 255))
    pygame.draw.rect(screen, (255,255,255), (*pos, 10, 10))
    pygame.display.flip()

Leave a Comment