Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 41 ยท Game Physics and Animation

Sprite Sheet Animation in Pygame

Animate characters in Pygame: slice a sprite sheet into frames, switch animations by state, time frames with delta time, flip for direction and build an Animation class.

A character that glides across the screen as a single still image feels lifeless. Animation is just a sequence of images shown one after another, a flip book. In games those images usually live together in one picture called a sprite sheet (or atlas), and your code cuts out the right piece at the right time.

You will learn to slice a sheet into frames, advance the frame by time rather than by loop count, switch between animations such as idle, run and jump, flip a character left or right, and wrap it all in a reusable class. Pygame's Surface, subsurface and Rect work without a window, so most of this lesson is runnable.

Why one sheet instead of many files

Loading 40 separate PNG files is slow and messy. One sheet loads in a single read, keeps related frames together and is friendlier to the GPU if you move to a faster renderer later.

flowchart LR
  S["player_sheet.png<br/>(4 columns x 3 rows)"] --> SL["Slice by cell size"]
  SL --> I["idle: 2 frames"]
  SL --> R["run: 4 frames"]
  SL --> J["jump: 2 frames"]
  I --> A["Animation player<br/>(frame timer)"]
  R --> A
  J --> A
  A --> D["blit current frame"]

Slice once at load time; choose the frame list by state at run time.

Slicing a sheet

If every frame has the same size, the frame in column c and row r is the rectangle (c * w, r * h, w, h):

Python
def slice_sheet(sheet, frame_w, frame_h):
    frames = []
    for y in range(0, sheet.get_height(), frame_h):
        row = []
        for x in range(0, sheet.get_width(), frame_w):
            row.append(sheet.subsurface((x, y, frame_w, frame_h)))
        frames.append(row)
    return frames        # frames[row][column]

subsurface shares pixels with the parent, so it costs almost nothing. Convert the sheet with convert_alpha() once after set_mode, so that blitting is fast.

You do not need artwork to try this. The next example draws a small sheet with Pygame (each cell is a different shade and a coloured square that shifts) and slices it, so you can inspect real surfaces and pixel colours.

Python Slice a generated sprite sheet

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The "drawn area" in the run row moves 3 pixels to the right each frame; in the idle row it grows. Those are the differences your eyes will read as motion.

Timing frames: by seconds, not by loop count

If you advance the frame on every loop iteration, a fast computer plays the animation too quickly. Count time instead, using delta time from Movement and Delta Time:

Python
class Animation:
    def __init__(self, frames, fps=8, loop=True):
        self.frames = frames
        self.frame_time = 1 / fps
        self.loop = loop
        self.timer = 0.0
        self.index = 0
        self.finished = False

    def update(self, dt):
        if self.finished:
            return
        self.timer += dt
        while self.timer >= self.frame_time:      # while, not if: handles slow frames
            self.timer -= self.frame_time
            self.index += 1
            if self.index >= len(self.frames):
                if self.loop:
                    self.index = 0
                else:
                    self.index = len(self.frames) - 1
                    self.finished = True

    @property
    def image(self):
        return self.frames[self.index]

    def reset(self):
        self.timer, self.index, self.finished = 0.0, 0, False

Use while rather than if so a long frame skips several animation frames and stays in sync. An fps of 6 to 12 suits pixel-art characters; smooth-looking motion rarely needs more.

Python Frame timing with different render rates

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

At every render rate the character steps through about eight frames per second. A non-looping animation (an explosion, a death) stops on its last frame and sets finished, which your game can use to remove the sprite.

Choosing the animation by state

A character is in one state at a time: idle, running, jumping, falling, attacking. Keep a dictionary of animations and pick the right one each frame; call reset() only when the state changes, otherwise the animation would restart forever on frame 0.

Python
class Player:
    def __init__(self, animations):
        self.animations = animations      # {"idle": Animation, "run": Animation, ...}
        self.state = "idle"
        self.facing_right = True

    def set_state(self, new_state):
        if new_state != self.state:
            self.state = new_state
            self.animations[new_state].reset()

    def choose_state(self):
        if not self.on_ground:
            self.set_state("jump" if self.vel.y < 0 else "fall")
        elif abs(self.vel.x) > 10:
            self.set_state("run")
        else:
            self.set_state("idle")

    def draw(self, surface):
        image = self.animations[self.state].image
        if not self.facing_right:
            image = pygame.transform.flip(image, True, False)
        surface.blit(image, self.rect)

You only need to draw frames facing right and flip them for the left. Cache flipped copies if profiling shows flip costing time.

Python State machine picks the animation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Frames 1 and 2 are both run and do not reset, so the run cycle keeps playing smoothly.

Tips for good animation

  • Anchor feet, not the center. Use rect.midbottom for positioning so a taller frame does not make the character jump.
  • Consistent frame size across the sheet keeps hit boxes simple. Use a separate, smaller collision rect instead of the picture rect.
  • Ping-pong loops (0,1,2,3,2,1) make a breathing idle with half the frames.
  • Pre-scale pixel art once with pygame.transform.scale (or scale_by) at load time, never every frame.
  • Tools: Aseprite, LibreSprite or Piskel export sheets plus JSON data that you can parse for frame rectangles and per-frame durations.
  • Frame data (rows, sizes, fps) belongs in a dictionary or JSON file, not scattered through the code.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why advance animation frames using accumulated time instead of once per loop iteration?

    A time-based timer shows a frame every 1/fps seconds regardless of the render rate.
  2. 2. What does surface.subsurface(rect) return?

    Subsurfaces reference the parent's pixel memory, so slicing a sheet is cheap.
  3. 3. When should you call reset() on an animation?

    Resetting every frame would freeze the animation on its first frame.
  4. 4. How do you draw a left-facing character if you only drew right-facing frames?

    flip with the first flag True mirrors the image horizontally.

Summary

  • Keep frames in one sprite sheet, and slice it once at load time with subsurface.
  • An Animation object advances by accumulated delta time and can loop or finish.
  • Pick the animation from the character's state, and reset only on state changes.
  • Flip frames for direction, anchor feet to the ground and keep collision boxes separate from art.

Next: Particles and Visual Effects