Search code examples
animationpygame

Pygame Animation Issue: Animation Keeps Looping Despite Flag


I'm working on a Pygame project where I have a player character with a simple animation. I want the animation to play once when the spacebar is pressed and then stop, but I'm encountering an issue where the animation keeps looping even though I set a flag to stop it.

import pygame
from sys import exit
from random import randint, choice

class Player(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.is_animating = False
        pk_1 = pygame.image.load('images/parryknight.png').convert_alpha()
        self.pk_2 = pygame.image.load('images/attack2.png').convert_alpha()
        self.pk_3 = pygame.image.load('images/attack3.png').convert_alpha()  
        self.pk_anim = [pk_1,self.pk_2,self.pk_3]
        self.pk_index = 0

        self.image = self.pk_anim[self.pk_index]
        self.rect = self.image.get_rect(midbottom = (80,420))
        self.gravity = 0

        self.jump_sound = pygame.mixer.Sound('music/swing.wav')
        self.jump_sound.set_volume(0.3)
    
    def player_input(self):
        keys = pygame.key.get_pressed()
        if self.pk_index < 0.1:
            if keys[pygame.K_SPACE]:
                self.jump_sound.play()

    def apply_gravity(self):
        self.gravity += 1
        self.rect.y += self.gravity
        if self.rect.bottom >= 420:
            self.rect.bottom = 420

    def animation_state(self):
        keys = pygame.key.get_pressed()
        self.is_animating = True
        if self.pk_index >= len(self.pk_anim):
            self.is_animating = False
            self.pk_index = 0
        self.image = self.pk_anim[int(self.pk_index)]
        
    def update(self):
        if self.is_animating == True:
            self.pk_index += 0.1
            if int(self.pk_index) >= len(self.pk_anim):
                self.is_animating = False
                self.pk_index = 0
        self.player_input()
        self.apply_gravity()
        self.animation_state()

I would appreciate any guidance on how to fix this issue and ensure that the animation stops after playing once when the spacebar is pressed.

Thank you in advance for your help!

Despite setting self.is_animating to False when the animation reaches the end, it keeps looping. I've tried various changes to the code, but I can't seem to get it to work as intended.


Solution

  • With this code:

    def animation_state(self):
        keys = pygame.key.get_pressed()
        self.is_animating = True
    

    Wouldn't you only want to set is_animating to True if a desired key is pressed? While your code does seem to turn the animation state off at the end of the animation, the moment this gets called, which I am assuming is within the game loop, it is just unconditionally setting it back to True.