Sprite animation

Cut a sprite sheet into frames and play them at a steady speed that doesn't depend on your frame rate, with idle and walking states and left/right facing.

Intermediate2 min readUpdated
On this page

What you'll learn

  • What a sprite sheet is and how to cut it into frames
  • Advancing frames with delta time instead of once per frame
  • Facing left and right without extra artwork
  • Switching between idle and walking animations

Prerequisites: Images and sprites.

Download the code and sprite sheet (ZIP)

Sprite sheets#

Animation is a sequence of still images (frames) shown quickly one after another. Instead of one file per frame, games usually store frames side by side in a single sprite sheet. One file loads faster and is easier to manage. Our sheet is 128 × 32 pixels: four 32 × 32 frames of a walk cycle.

The four frames of the walk cycle above a scaled-up walking character
sprite_animation.py showing the frames from walk_sheet.png

You can build sheets from individual images with the sprite sheet generator, which also produces matching loading code.

Cutting frames with subsurface#

sheet.subsurface((x, y, w, h)) returns a Surface that shares pixels with the sheet, so cutting is instant and uses no extra memory. Scaling or flipping creates independent copies.

sprite_animation.pyDownload
"""Cutting a sprite sheet into frames and playing a walk cycle at its own speed."""
from pathlib import Path

import pygame

ASSETS = Path(__file__).parent / "assets"
WIDTH, HEIGHT = 640, 360
FRAME_SIZE = 32
SCALE = 4
ANIMATION_FPS = 8       # frames of animation per second, independent of the game FPS


def load_frames(path, frame_w, frame_h, scale):
    sheet = pygame.image.load(path).convert_alpha()
    frames = []
    for x in range(0, sheet.get_width(), frame_w):
        frame = sheet.subsurface((x, 0, frame_w, frame_h))
        frames.append(pygame.transform.scale_by(frame, scale))
    return frames


class Walker(pygame.sprite.Sprite):
    def __init__(self, frames, pos):
        super().__init__()
        self.frames_right = frames
        self.frames_left = [pygame.transform.flip(f, True, False) for f in frames]
        self.index = 0.0
        self.facing = 1
        self.image = frames[0]
        self.rect = self.image.get_rect(midbottom=pos)

    def update(self, dt, direction):
        if direction:
            self.facing = direction
            self.rect.x += round(direction * 160 * dt)
            self.index = (self.index + ANIMATION_FPS * dt) % len(self.frames_right)
        else:
            self.index = 0                                   # stand still on frame 0
        frames = self.frames_right if self.facing > 0 else self.frames_left
        self.image = frames[int(self.index)]
        if self.rect.left > WIDTH:
            self.rect.right = 0
        elif self.rect.right < 0:
            self.rect.left = WIDTH


pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
font = pygame.font.Font(None, 26)
frames = load_frames(ASSETS / "walk_sheet.png", FRAME_SIZE, FRAME_SIZE, SCALE)
walker = Walker(frames, (WIDTH // 2, 300))

running = True
while running:
    dt = clock.tick(60) / 1000
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    keys = pygame.key.get_pressed()
    direction = keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]
    walker.update(dt, direction)

    screen.fill((40, 48, 80))
    pygame.draw.rect(screen, (90, 110, 150), (0, 300, WIDTH, 60))
    screen.blit(walker.image, walker.rect)
    for i, f in enumerate(frames):                            # show the frames under the scene
        screen.blit(pygame.transform.scale_by(f, 0.5), (16 + i * 70, 16))
    screen.blit(font.render(f"Frame {int(walker.index)}   Left/Right to walk", True, (230, 236, 247)), (320, 30))
    pygame.display.flip()

pygame.quit()

Timing animation independently of FPS#

A naive animation advances one frame per game frame. At 60 FPS a 4-frame walk cycle then loops 15 times per second, far too fast, and the speed changes with the frame rate.

Instead keep a float index and advance it by ANIMATION_FPS * dt. With ANIMATION_FPS = 8 the animation shows 8 frames per second on any computer. int(self.index) picks the frame and % len(frames) wraps around to the start.

Facing direction and states#

The walker remembers facing (1 or -1) and keeps two frame lists, the originals and horizontally flipped copies made once at load time. When no key is held it resets to frame 0, a simple idle pose.

Larger games keep a dictionary of animations and a current state:

Python
self.animations = {"idle": idle_frames, "walk": walk_frames, "jump": jump_frames}
...
new_state = "jump" if not self.on_ground else "walk" if moving else "idle"
if new_state != self.state:
    self.state = new_state
    self.index = 0          # start the new animation from its first frame
frames = self.animations[self.state]
self.image = frames[int(self.index) % len(frames)]

Resetting the index on a state change keeps animations from starting halfway through.

Keeping the feet in place#

If frames have different sizes, setting self.rect = self.image.get_rect() every frame makes the sprite jump around. Anchor it instead: self.rect = self.image.get_rect(midbottom=self.rect.midbottom) keeps the feet on the same spot while the image changes.

Common mistakes#

  • Animating in draw instead of update: animation is game state; update it with dt.
  • Flipping every frame: pygame.transform.flip creates a new Surface each call. Prepare flipped frames once.
  • Index out of range: when switching to an animation with fewer frames, wrap the index with % or reset it.
  • Blurry pixel art: scale with scale_by, not smoothscale.

Practice exercises#

  1. Draw a 2-frame idle animation in the pixel art editor and play it at 2 FPS when standing still.
  2. Make the animation speed proportional to movement speed (run faster, animate faster).
  3. Add a one-shot "wave" animation on the W key that returns to idle when it finishes.
  4. Load frames using the JSON exported by the sprite sheet generator.
↑ ↓ to moveEnter to openEsc to close