敌人精灵不会向左翻转

Enemy sprite will not flip left

我有一个使用下面的函数左右遍历的精灵。当它向左翻转时,它会将 img 翻转 1 帧,然后在向左移动时保持指向右侧。同样的 1 帧翻转也发生在另一侧。对于单个图像,效果很好,但我添加了这个动画循环,现在我很困惑。

class Enemy(pygame.sprite.Sprite):#==================================================
    def __init__(self,x,y):   
        pygame.sprite.Sprite.__init__(self)
        self.images_right = []
        self.frame_index = 0
        self.counter = 0
        for num in range (1,8):
            img_right = pygame.image.load(f'img/enemy/{num}.png')   
            self.images_right.append(img_right)
        self.image = self.images_right[self.frame_index]
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
        self.move_direction = 1
        self.move_counter = 0

    def update(self):
        self.counter += 1
        walk_cooldown = 2
        if self.counter > walk_cooldown:
            self.counter = 0
            self.frame_index += 1
            if self.frame_index >= len(self.images_right):
                self.frame_index = 0
            self.image = self.images_right[self.frame_index]
        self.rect.x += self.move_direction
        self.move_counter += 1
        if abs(self.move_counter) > 32:
            self.move_direction *= -1
            self.image = pygame.transform.flip(self.image, True, False)  
            self.move_counter *= -1

您有一张图片列表。您只是翻转了列表中的最后一张图片。

在构造函数中,创建左右图像列表和select要在update中显示的图像:

class Enemy(pygame.sprite.Sprite):
    def __init__(self,x,y):   
        pygame.sprite.Sprite.__init__(self)
        
        self.images_right = [pygame.image.load(f'img/enemy/{num}.png') for num in range (1,8)]
        self.images_left = [pygame.transform.flip(img, True, False) for img in self.images_right]
        
        self.frame_index = 0
        self.image = self.images_right[self.frame_index]
        self.rect = self.image.get_rect(topleft = (x, y))   
        self.counter = 0
        self.move_direction = 1
        self.move_counter = 0

    def update(self):
        self.counter += 1
        walk_cooldown = 2
        if self.counter > walk_cooldown:
            self.counter = 0
            self.frame_index += 1
            if self.frame_index >= len(self.images_right):
                self.frame_index = 0
        self.rect.x += self.move_direction
        self.move_counter += 1
        if abs(self.move_counter) > 32:
            self.move_direction *= -1
            self.move_counter *= -1

        image_list = self.images_right if self.move_direction > 0 else self.images_left    
        self.image = image_list[self.frame_index]