素材準備:(https://github.com/yjmyzz/pygame_tutorial)
角色動畫的原理:動畫都是一幀幀渲染的,比如向左走的動畫窟蓝,實際是類似上圖中的L1.png~L9png 連續(xù)切換偎痛,由于肉眼視覺暫留的作用挥唠,所以看上去象連續(xù)的動畫。
import pygame
from pygame.locals import *
import sys
# 初始化pygame
pygame.init()
size = (800, 600)
# 設置屏幕寬高
screen = pygame.display.set_mode(size)
# 設置屏幕標題
pygame.display.set_caption("my first game")
black = 0, 0, 0
clock = pygame.time.Clock()
listLeft = [pygame.image.load('img/actor/L{}.png'.format(i)).convert_alpha() for i in range(1, 10)]
listRight = [pygame.image.load('img/actor/R{}.png'.format(i)).convert_alpha() for i in range(1, 10)]
imgHero = pygame.image.load('img/standing.png').convert_alpha()
xPos = 100
speed = 2
# 左direction = 1民褂,右direction = 2试疙,前direction = 0
direction = 0
indexLeft = 0
indexRight = 0
while True:
clock.tick(10)
# 啟動消息隊列诵棵,獲取消息并處理
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
keys = pygame.key.get_pressed()
if keys[K_LEFT]:
direction = 1
xPos -= speed
print('left')
elif keys[K_RIGHT]:
direction = 2
xPos += speed
print('right')
else:
direction = 0
screen.fill((0, 0, 0))
if direction == 0:
screen.blit(imgHero, (xPos, 100))
elif direction == 1:
screen.blit(listLeft[indexLeft % 9], (xPos, 100))
indexLeft += 1
elif direction == 2:
screen.blit(listRight[indexRight % 9], (xPos, 100))
indexRight += 1
pygame.display.update()
image.gif