如何为精灵设置动画?

how to animate the sprite?

    from numpy import size
import pygame
import sys

# --- constants ---  # PEP8: `UPPER_CASE_NAMES` for constants

WHITE = (255, 255, 255)   # PE8: space after `,`
SIZE = (700, 500)
FPS = 120  # there is no need to use `500` because Python can't run so fast,
           # and monitors runs with 60Hz (eventually 120Hz) which can display 60 FPS (120 FPS)

# --- classes ---  # PEP8: `CamelCaseNames` for classes

class MySprite(pygame.sprite.Sprite):
    
    def __init__(self, x, y, picture, colorkey):
        super().__init__()
        
        # you need one of them
        
        # load image
        self.image = pygame.image.load(picture)
        
        # OR

        # create surface        
        # self.image = pygame.Surface((10, 10))
        # self.image.fill((255, 0, 0))
        
        # ----
        
        self.rect = self.image.get_rect()
        self.rect.center = (x, y)

        self.image.set_colorkey(colorkey)
    def update(self):
        if event.type == pygame.MOUSEBUTTONDOWN:
            mouse = pygame.mouse.get_pos()
            print(mouse[:])

# --- main ---

pygame.init()
window_game = pygame.display.set_mode(SIZE)
backGround = pygame.image.load('bg.jpg').convert_alpha(window_game)
backGround = pygame.transform.smoothscale(backGround,SIZE)
backGround.set_colorkey(WHITE)

#placeSP_group = pygame.sprite.Group()
placeSP_group = pygame.sprite.OrderedUpdates()  # Group which keep order

sprite1 = [MySprite(0, 0, 'crossHair.png', WHITE),MySprite(0, 0, 'crossHair_2.png', WHITE)]

placeSP_group.add([sprite1[0],sprite1[1]])
pygame.mouse.set_visible(False)

clock = pygame.time.Clock()   # PEP8: `lower_case_names` for variables

running = True

while running:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            #running = False
            pygame.quit()
            exit()
            
    # create new Sprite
    global x,y
    x, y = pygame.mouse.get_pos()
    new_sprite = sprite1[:]
    
    # add new Sprite at the end of OrderedUpdates()
    placeSP_group.add([new_sprite])
    # remove Sprite at the beginning of OrderedUpdates()
    placeSP_group.sprites()[0].kill()  
     
    
    placeSP_group.update() 

    # ---

    pygame.display.flip()
    
    window_game.fill('white') 
    window_game.blit(backGround,(0,0)).size
    
    placeSP_group.draw(window_game)
    
    clock.tick(FPS)

当我将 new_sprite 指定给 placeSP 中的所有指定精灵时 它没有显示任何东西,你能帮我解决这个问题吗?我不确定为什么会这样,但你能解决它吗……这是一个经过编辑的问题。我没有得到任何答案....但我脑子里有这个概念,我也不想修改我的代码那么多你能帮我吗...

创建一个带有图像列表的 sprite class。添加一个计算帧数的属性。根据帧数update方法从图像列表中获取图像:

class MySprite(pygame.sprite.Sprite):
    
    def __init__(self, x, y, image_list):
        super().__init__()
        self.frame = 0
        self.image_list = image_list
        self.image = self.image_list[0]
        self.rect = self.image.get_rect()
        self.rect.center = (x, y)

    def update(self, event_list):

        animation_interval = 20
        self.frame += 1
        if self.frame // animation_interval >= len(self.image_list):
            self.frame = 0
        self.image = self.image_list[self.frame // animation_interval]
        
        for event in event_list:
            if event.type == pygame.MOUSEBUTTONDOWN:
                mouse = event.pos
                print(mouse[:])

但是,您需要在应用程序循环之前创建一次精灵,而不是每帧不断地创建和 killing 精灵。更改精灵的位置并在应用程序循环中更新精灵:

file_list = ['crossHair.png', 'crossHair_2.png', 'crossHair_3.png']
image_list = []
for name in file_list:
    image = pygame.image.load(name)
    image.set_colorkey(WHITE)
    image_list.append(image)

# create sprite
sprite1 = MySprite(0, 0, image_list)
placeSP_group = pygame.sprite.OrderedUpdates()
placeSP_group.add([sprite1])

clock = pygame.time.Clock()
running = True
while running:

    # handle events
    event_list = pygame.event.get()
    for event in event_list:
        if event.type == pygame.QUIT:
            running = False
            
    # update sprite
    x, y = pygame.mouse.get_pos()   
    placeSP_group.sprites()[0].rect.center = (x, y)     
    placeSP_group.update(event_list) 
    
    # draw scene
    window_game.fill('white') 
    window_game.blit(backGround,(0,0)).size
    placeSP_group.draw(window_game)
    pygame.display.flip()
    
    clock.tick(FPS)

pygame.quit()
exit()

另请参阅:

  • how to create an illusion of animations in pygame
  • Animated sprite from few images
  • How do I create animated sprites using Sprite Sheets in Pygame?