samiles
samiles

Reputation: 3900

Alternate an image while it's moving in Pygame

I have this image in Pygame which moves around the screen. What I want to do is alternate every other time. So, I want it to start off as image1.png and then move across the page, switching between human1.png and human2.png and finish up back on image1.png. Is this possible?

My code is:

if (human1_position.left <= 555):
    human1_position = human1_position.move(2, 0)  # move first human
    pygame.display.update()
else:
    move = STOP
screen.blit(human1, human1_position)

Thanks

Upvotes: 0

Views: 384

Answers (1)

pmoleri
pmoleri

Reputation: 4451

Here is a possible solution:

# Before main loop
human_files = ["human1.png", "human2.png"]
human_sprites = [pygame.image.load(filename).convert_alpha() for filename in human_files]
human1_index = 0

...

# During main loop
if (human1_position.left <= 555):
    human1_position = human1_position.move(2, 0)  # move first human
    human1_index = (human_index + 1) % len(human_sprites) # change sprite
else:
    move = STOP
    human1_index = 0
human1 = human_sprites[human1_index]
screen.blit(human1, human1_position)
pygame.display.update()

I moved the update() call, it should occur only once per frame after all has been drawn.

Upvotes: 1

Related Questions