Search code examples
imageanimationpygamesprite-sheet

Controlling sprite animation with keypress


I've been working on a boxing game. After spending hours creating a sprite sheet, I now have trouble using it in my game. The animations load fine, but I can't seem to find a good way to control them. I would like to have each line of my sprite_sheet loop only once, but using this code, the punch keeps looping until I release the key.

left_jab = False

for event in pygame.event.get():

   if event.type == pygame.QUIT:
       quit()

   elif event.type == pygame.KEYDOWN:

       if event.key == pygame.K_UP:
           left_jab = True

   elif event.type == pygame.KEYUP:

       if event.key == pygame.K_UP:
           left_jab = False

   if left_jab:
        player.update(dt)
        player.render_left_jab(gameDisplay)

This is part of the player class:

    def update(self, dt):

    self.current_time += dt

    if self.current_time >= self.animation_time:
        self.current_time = 0

        if self.current_image >= self.numImages - 1:
            self.current_image = 0

        else:
            self.current_image += 1

Is there an easier way to do this? There are 8 images per line in my sprite sheet. Is it just a matter of creating a smoother animation using more images?


Solution

  • Think about how long the animation (or the punching) should take, and if that time is up, set left_jab to False again.

    A very simple way is to change your code to something like:

    if self.current_image >= self.numImages - 1:
        self.current_image = 0
        left_jab = False
    

    So once the animation looped once, we just stop it.

    Of course this is not the final solution, but you'll get the idea. You didn't show your full code but I suggest moving all logic that belongs to the player/boxer entity into its class (the check for key presses, the left_jab flag etc.).