First off, yes I’m a noob but I have ready meany tutorials on getting a character to jump which doesn’t seem too complicated but it’s not working. The character keeps incrementing up the screen.
It seems the biggest challenge is using a usb controller but I don’t want to use a keyboard to controll the character’s movement.
Any help here would be greatly appreciated. Just to get this far it took me a week…
import pygame
pygame.init()
size = (800,600)
screen = pygame.display.set_mode(size)
clock = pygame.time.Clock()
x = 50
y = 550
width = 50
height = 50
speed = 5
joystick = None
vel = 5
isJump = False
jumpCount = 0
done = False
while not done:
clock.tick(100)
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(4))
if abs(axis_x) > 0.1:
x += speed * axis_x
#if abs(axis_y) > 0.1:
# pos[1] += speed * axis_y
buttons = joystick.get_numbuttons()
for i in range( buttons ):
button = joystick.get_button( i )
if button == 1:
isJump = True
jumpCount = 10
if isJump:
if jumpCount > 0:
y -= 5
elif jumpCount <= 0:
y += 5
jumpCount -= 1
if jumpCount == -10:
isJump = False
else:
if pygame.joystick.get_count() > 0:
joystick = pygame.joystick.Joystick(0)
joystick.init()
print("joystick initialized")
screen.fill((0, 0, 0))
pygame.draw.rect(screen, (255,255,255), (x, y, width, height))
pygame.display.flip()
pygame.display.update()
pygame.quit()
>Solution :
Your problem has nothing to do with the USB controller. Pressing the button triggers the jump. It only sets isJump. But as soon as the jump is started, it must be calculated in the application loop. Also see How to make a character jump in Pygame?:
isJump = False
jumpCount = 0
done = False
while not done:
clock.tick(100)
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(4))
if abs(axis_x) > 0.1:
x += speed * axis_x
buttons = joystick.get_numbuttons()
for i in range( buttons ):
button = joystick.get_button( i )
if button == 1 and not isJump: # <---
isJump = True
jumpCount = 10
else:
if pygame.joystick.get_count() > 0:
joystick = pygame.joystick.Joystick(0)
joystick.init()
print("joystick initialized")
if isJump: # <---
if jumpCount > 0:
y -= 5
elif jumpCount <= 0:
y += 5
jumpCount -= 1
if jumpCount == -10:
isJump = False
screen.fill((0, 0, 0))
pygame.draw.rect(screen, (255,255,255), (x, y, width, height))
pygame.display.flip()
pygame.display.update()
pygame.quit()
