python动画精灵_Python pygame精灵动画

本文介绍如何在Python的Pygame库中实现精灵动画。通过加载精灵表(sheet.png),定义精灵类并更新计数器来切换不同帧,从而实现动画效果。代码示例展示了如何创建一个125x125像素的精灵,每秒显示16帧。
摘要由CSDN通过智能技术生成

你在瞎说字符.图像在屏幕上:screen.blit(character.images,(30,100))

以下是类变量包含的内容:

^{pr2}$

此变量从不更新,因此自然不会显示任何动画。在

以下是我使用this image作为精灵表的实现:import pygame, sys

from pygame.locals import *

sheet = 'sheet.png'

pygame.init()

screen = pygame.display.set_mode((500, 500))

FPS = 30

FPSCLOCK = pygame.time.Clock()

class Character(object):

def __init__(self, sheet, width, height, end):

self.sheet = pygame.image.load(sheet)

self.width = width

self.height = height

self.end = end

self.counterX = 0

self.counterY = 0

self.imageWidth = self.sheet.get_rect().size[0]

self.imageHeight = self.sheet.get_rect().size[1]

self.spritesPerRow = self.imageWidth / self.width

self.spritesPerCol = self.imageHeight / self.height

# These assertions will raise an exception if image size, sprite size

# and sprite count don't add up as they should be. You can experiment

# with this by changing the values when this object is instantiated.

assert self.imageWidth % self.width == 0, 'Incorrect sprite width!'

assert self.imageHeight % self.height == 0, 'Incorrect sprite height!'

assert self.spritesPerRow * self.spritesPerCol == self.end, \

'Incorrect number of sprites!'

def update(self):

# The counters keep track of which sprite to display from the

# sprite sheet.

self.spriteArea = (self.counterX * self.width,

self.counterY * self.height,

self.width, self.height)

self.counterX += 1

if self.counterX == self.spritesPerRow:

self.counterX = 0

self.counterY += 1

if self.counterY == self.spritesPerCol:

self.counterX = 0

self.counterY = 0

Test = Character(sheet, 125, 125, 16)

# Displays the sprite sheet for one second.

screen.blit(Test.sheet, (0, 0))

pygame.display.update()

pygame.time.wait(1000)

while True:

for event in pygame.event.get(QUIT):

pygame.quit()

sys.exit()

screen.fill((255, 255, 255))

Test.update()

screen.blit(Test.sheet, (188, 188), Test.spriteArea)

pygame.display.update()

FPSCLOCK.tick(FPS)

免责声明:

我也是一个Pygame/Python新手,我不知道这种方法是否有效。。。但至少它能如愿工作!在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值