Cut a Sprite Sheet
Part of the Sprites and Images section of Coddy's Pygame journey. Lesson 26 of 39.
Animation is a few pictures shown one after another. Games often keep those pictures in one file, a sprite sheet: a grid of small frames packed side by side. The starter draws assets/sheets/platformer_characters.png whole, 9 frames across and 3 down, each 24 by 24 pixels. The green character's two walking poses are the first two in the top row.
sheet.subsurface(rect) gives you the part of the sheet inside a Rect, as a Surface of its own, without copying a pixel. Frame number col in row row starts at (col * 24, row * 24):
frames = []
for col in (0, 1):
frame = sheet.subsurface((col * 24, 0, 24, 24))
frames.append(pygame.transform.scale_by(frame, 3))24 pixels is tiny on a 640 by 480 window, so each frame is scaled by 3 to 72 by 72. Pixel art scaled by a whole number keeps its sharp edges. Cut and scale once, before the loop, and keep the frames in a list: the next lessons pick one by its index.
Challenge
MediumCut two walking frames out of the sheet.
- Before the loop, make
frames: the frames at columns 0 and 1 of the top row, each 24 by 24, scaled by 3. - Instead of the whole sheet, draw
frames[0]at(200, 200)andframes[1]at(368, 200).
Press Play: two big walking frames. Then Check.
Try it yourself
import pygame
pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Sprite Sheet")
clock = pygame.time.Clock()
sheet = pygame.image.load("assets/sheets/platformer_characters.png").convert_alpha()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill((20, 22, 40))
screen.blit(sheet, (212, 204))
pygame.display.flip()
clock.tick(60)
pygame.quit()
All lessons in Sprites and Images
Practice on your own: Pygame playground