Pygame基础3-动画

简介: Pygame基础3-动画

3.动画

原理

动画是连续播放的图片

使用精灵显示动画只需要在update()方法中改变精灵的图片。

需要注意的是播放速度,可以

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


用到的图片

案例

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

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)


相关文章
|
17天前
|
存储 缓存 开发者
如何利用Pygame实现动画效果?
【6月更文挑战第10天】如何利用Pygame实现动画效果?
13 1
|
1月前
|
Python
python小项目之利用pygame实现代码雨动画效果(附源码 可供学习)
python小项目之利用pygame实现代码雨动画效果(附源码 可供学习)
95 1
|
Python
Python 使用 pygame 实现一个简单的动画
首先安装pygame库: $ sudo pip install pygame 测试安装效果: #导入pygame模块 import pygame #初始化pygame pygame.init() #创建舞台,利用Pygame中的display模块,来创建窗口 screen = pygame.display.set_mode((640,480),0,32) #设置窗口标题 pygame.display.set_caption("Hello PyGame") 这个时候大家运行就能得到一个窗口但是窗口一闪而过。
1618 0
|
Python
pygame学习笔记(2)——从画点到动画
转载请注明:@小五义 http://www.cnblogs.com/xiaowuyi 1、单个像素(画点)利用pygame画点主要有三种方法:方法一:画长宽为1个像素的正方形 #@小五义 http://www.
1050 0
|
1月前
|
存储 人工智能 算法
使用 Python 和 Pygame 制作游戏:第九章到第十章
使用 Python 和 Pygame 制作游戏:第九章到第十章
62 0
使用 Python 和 Pygame 制作游戏:第九章到第十章
|
1月前
|
Python
Python使用pygame播放MP3
Python使用pygame播放MP3
45 0
|
1月前
|
定位技术 Python
【python】pygame实现植物大战僵尸小游戏(附源码 有注释)
【python】pygame实现植物大战僵尸小游戏(附源码 有注释)
801 1
|
6天前
|
开发框架 Python
Python的`pygame`库用于2D游戏开发,涵盖图形、音频和输入处理。
【6月更文挑战第21天】Python的`pygame`库用于2D游戏开发,涵盖图形、音频和输入处理。要开始,先通过`pip install pygame`安装。基本流程包括:初始化窗口、处理事件循环、添加游戏元素(如玩家和敌人)、响应用户输入、更新游戏状态及结束条件。随着项目发展,可逐步增加复杂性。
17 1

热门文章

最新文章