I have it so that my character will play a walking animation when they move left or right, and when they stop moving they are idle. The animation part works fine, but when I let go of left/right, it still plays and the player never goes idle. The code for my player animation and player controls are below.
def animation_state():
global player_surface, player_index, player_rect
player_index = 0.15
if player_index >= len(player_right_walk):
player_index = 0
if LEFT == True:
player_surface = player_left_walk[int(player_index)]
elif RIGHT == True:
player_surface = player_right_walk[int(player_index)]
if LEFT == False and RIGHT == False:
player_surface = pygame.image.load('graphics/dino_idle_right.png').convert_alpha()
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
player_surface = pygame.image.load('graphics/dino_idle_left.png').convert_alpha()
elif event.key == pygame.K_RIGHT:
player_surface = pygame.image.load('graphics/dino_idle_right.png').convert_alpha()
screen.blit(player_surface,player_rect)
player control
def player_control():
global LEFT, RIGHT
player_velocity = 0
player_gravity = 0
player_gravity = 3
player_rect.y = player_gravity
if player_rect.bottom >= 500:
player_rect.bottom = 500
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
player_velocity -= 11
LEFT = True
RIGHT = False
if player_rect.x < -50:
player_rect.x = 800
elif keys[pygame.K_RIGHT]:
player_velocity = 11
LEFT = False
RIGHT = True
if player_rect.x > 800:
player_rect.x = -50
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or pygame.K_RIGHT:
player_velocity = 0
player_rect.x = player_velocity
CodePudding user response:
Because you do not reset LEFT
and RIGHT
if no key is pressed. Set LEFT
and RIGHT
to False before checking the keys. Set LEFT
or RIGHT
depending on the key that is pressed:
def player_control():
# [...]
keys = pygame.key.get_pressed()
LEFT = False
RIGHT = False
if keys[pygame.K_LEFT]:
player_velocity -= 11
LEFT = True
if player_rect.x < -50:
player_rect.x = 800
elif keys[pygame.K_RIGHT]:
player_velocity = 11
RIGHT = True
if player_rect.x > 800:
player_rect.x = -50