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)

相关推荐

  1. 基于Python的pygame库的五子棋游戏

    2024-03-25 12:32:03       31 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-25 12:32:03       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-25 12:32:03       106 阅读
  3. 在Django里面运行非项目文件

    2024-03-25 12:32:03       87 阅读
  4. Python语言-面向对象

    2024-03-25 12:32:03       96 阅读

热门阅读

  1. [小程序开发] 消息提示模块封装

    2024-03-25 12:32:03       34 阅读
  2. 云主机下搭建网页爬虫

    2024-03-25 12:32:03       33 阅读
  3. 3.21 ARM day5

    2024-03-25 12:32:03       37 阅读
  4. C++中类和对象其他内容

    2024-03-25 12:32:03       31 阅读
  5. springboot 整合 Caffine(springboot3.2)

    2024-03-25 12:32:03       42 阅读
  6. 完全背包,LeetCode322. 零钱兑换

    2024-03-25 12:32:03       34 阅读
  7. QT 常用模块介绍以及使用说明

    2024-03-25 12:32:03       40 阅读
  8. 小程序配置服务器域名

    2024-03-25 12:32:03       42 阅读
  9. vscode配置rp2040出错记录

    2024-03-25 12:32:03       37 阅读