In a simple pygame zero 2D game, I have a list of Actors that I'm looping through to ensure that they don't run off the side of the screen. However, going right, only the leftmost item in the list (the first one) is triggering the direction change--the rest run off the screen. Strangely, it works fine when they're moving left.
I'm running this code (except the function at the bottom) in the update() function. The enemies are 48 pixels wide.
Edit: I looked in the debugger and it seems the for loop never gets to the second enemy in the list. It's just constantly checking the first one.
WIDTH = 800
HEIGHT = 600
gameDisplay = pygame.display.set_mode((WIDTH, HEIGHT))
...
for enemy in enemies:
if enemy.x >= WIDTH - 50 or enemy.x <= 50:
# change enemy direction
enemy_direction *= -1
break
else:
animate_sideways(enemies)
...
def animate_sideways(enemies):
for enemy in enemies:
enemy.x += enemy_direction
You can not determine the direction in which the enemies should move and move the enemies in the same loop. First you need to set the common direction of movement. After that you can move all enemies in this direction. animate_sideways
itself has a loop that moves all enemies and must be called after the direction is changed:
# Determine whether the common direction of movement must be changed
for enemy in enemies:
if enemy.x >= WIDTH - 50 or enemy.x <= 50:
# change enemy direction
enemy_direction *= -1
break
# Move all enemies in the same direction
animate_sideways(enemies)