I coded a jumping motion for my character, however, instead of one proper fluid motion the changes come every time I press the Up Arrow Key. I have tried making the code using a while loop, but the screen freezes then. I tried making the code an event and then calling it, no luck. I even got desperate and tried watching a YouTube video and looking at the question solved right here on Stack Overflow but I couldn’t solve my problem. Here is the code:
#Variables
player_img = pygame.image.load('car.png')
player_x = 40
player_y = 390
vel = 5
isJump = False
jumpCount = 10
player_pass_range = range(10,21)
class Player():
def draw_player():
screen.blit(player_img, (player_x, player_y))
#Main Loop
while playing:
screen.fill((0, 0, 255))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running, playing, credits_menu, options_menu = False, False, False, False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
if jumpCount >= -10:
player_y -= (jumpCount * abs(jumpCount)) * 0.5
jumpCount -= 1
else: # This will execute if our jump is finished
jumpCount = 10
isJump = False
#Draw Objects
Player.draw_player()
#Update Screen
pygame.display.update()
clock.tick(60)
>Solution :
See How to make a character jump in Pygame?
The jump animation must be done in the application loop instead of the event loop. Set isJump to True when the key is pressed. Animate the player in the application loop depending on isJump:
while playing:
screen.fill((0, 0, 255))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running, playing, credits_menu, options_menu = False, False, False, False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
isJump = True
if isJump:
if jumpCount >= -10:
player_y -= (jumpCount * abs(jumpCount)) * 0.5
jumpCount -= 1
else: # This will execute if our jump is finished
jumpCount = 10
isJump = False
# [...]