前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Pygame基础3-动画

Pygame基础3-动画

作者头像
一只大鸽子
发布2024-03-25 14:19:39
710
发布2024-03-25 14:19:39
举报

3.动画

原理

动画是连续播放的图片。使用精灵显示动画只需要在update()方法中改变精灵的图片。需要注意的是播放速度,可以

  • • 通过pygame.time.get_ticks()来控制时间,但是这样比较复杂。
  • • 最直接的方式是根据帧数来控制播放。每过n帧就切换一次图片。
动画
动画

用到的图片[1]

案例

我们使用一个精灵类实现动画。当按下任意键时,开始播放动画。

代码语言:javascript
复制
import pygame, sys

class Player(pygame.sprite.Sprite):
    def __init__(self, pos_x, pos_y):
        super().__init__()
        self.attack_animation = False
        self.sprites = [ pygame.image.load(f'attack_{i}.png') for i in range(1,11)] 
    
        self.current_sprite = 0
        self.image = self.sprites[self.current_sprite]

        self.rect = self.image.get_rect()
        self.rect.topleft = [pos_x,pos_y]

    def attack(self):
        self.attack_animation = True

    def update(self,speed):
        if self.attack_animation == True:
            self.current_sprite += speed
            if int(self.current_sprite) >= len(self.sprites):
                self.current_sprite = 0
                self.attack_animation = False

        self.image = self.sprites[int(self.current_sprite)]

# General setup
pygame.init()
clock = pygame.time.Clock()

# Game Screen
screen_width = 400
screen_height = 400
screen = pygame.display.set_mode((screen_width,screen_height))
pygame.display.set_caption("Sprite Animation")

# Creating the sprites and groups
moving_sprites = pygame.sprite.Group()
player = Player(100,100)
moving_sprites.add(player)

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if event.type == pygame.KEYDOWN:
            player.attack()

    # Drawing
    screen.fill((0,0,0))
    moving_sprites.draw(screen)
    moving_sprites.update(0.25)
    pygame.display.flip()
    clock.tick(60)
引用链接

[1] 用到的图片: https://opengameart.org/content/opp2017-sprites-characters-objects-effects

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2024-03-25,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 一只大鸽子 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 3.动画
  • 原理
  • 案例
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档