Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 41 ยท Game Physics and Animation

Particles and Visual Effects in Pygame

Add polish to Pygame games: particle systems, snowfall, explosions, color breathing, screen shake and math art such as Rhodonea curves and the Maurer rose.

Particle effects are the cheap trick behind most of the visual polish you notice in games: sparks when a bullet hits, dust when a character lands, smoke, rain, snow, stars. A particle is just a tiny object with a position, a velocity and a limited lifetime. Draw a few hundred of them and the screen comes alive.

This lesson builds a reusable particle system, then uses the same ideas for snowfall, a color "breathing" effect, screen shake and some mathematical curves. The drawing code is shown read-only; the update rules are runnable simulations, because that is where the real logic lives.

Anatomy of a particle

flowchart LR
  E["Emitter<br/>(spawns particles)"] --> P["Particle<br/>pos, vel, life, size, colour"]
  P --> U["update(dt)<br/>move, shrink, fade"]
  U --> D{"life <= 0?"}
  D -- yes --> R["remove from list"]
  D -- no --> W["draw"]

Every frame: spawn some, update all, remove the dead, draw the rest.

Python
import random
import pygame
from pygame.math import Vector2

class Particle:
    def __init__(self, pos, vel, life, size, colour):
        self.pos = Vector2(pos)
        self.vel = Vector2(vel)
        self.life = self.max_life = life        # seconds
        self.size = size
        self.colour = colour

    def update(self, dt):
        self.vel.y += 400 * dt                  # a little gravity
        self.pos += self.vel * dt
        self.life -= dt

    def draw(self, surface):
        t = max(self.life / self.max_life, 0)   # 1.0 -> 0.0 over the lifetime
        radius = max(1, int(self.size * t))     # shrink as it ages
        pygame.draw.circle(surface, self.colour, self.pos, radius)

Notice t, the normalized age. Almost every effect is a function of t: size, brightness, colour and speed can all be tied to it.

Python
particles = []

def burst(pos, count=30):
    for _ in range(count):
        angle = random.uniform(0, 360)
        speed = random.uniform(80, 260)
        vel = Vector2(speed, 0).rotate(angle)
        particles.append(Particle(pos, vel, random.uniform(0.4, 0.9),
                                  random.randint(3, 6), (255, random.randint(120, 220), 60)))

# per frame
for p in particles:
    p.update(dt)
particles[:] = [p for p in particles if p.life > 0]   # keep the living

Rebuild the list with a comprehension instead of calling remove inside a for loop, which skips items. Cap the list size (for example 500) so that a flurry of explosions cannot ruin the frame rate.

Python A particle burst, simulated

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 count drops as particles reach the end of their lifetime, and their average y rises as gravity pulls them down.

Snowfall

Snow is a particle system with no emitter bursts: flakes spawn along the top edge, drift down at different speeds (slow flakes read as distant) and wrap around when they leave the screen. A little sideways sine wave makes them sway.

Python
import math, random

flakes = [[random.uniform(0, W), random.uniform(0, H),
           random.uniform(20, 90),            # fall speed
           random.randint(1, 4),              # radius
           random.uniform(0, math.tau)]       # sway phase
          for _ in range(150)]

for f in flakes:
    f[1] += f[2] * dt
    f[0] += math.sin(t * 1.5 + f[4]) * 15 * dt
    if f[1] > H + 5:
        f[0], f[1] = random.uniform(0, W), -5
    pygame.draw.circle(screen, (240, 245, 255), (int(f[0]), int(f[1])), f[3])

Tie speed and size together (bigger means faster and closer) to get a convincing sense of depth, a trick known as parallax.

Python Snowfall wrapping logic

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.

Colour breathing

Smoothly pulsing a colour from dark to bright adds life to buttons and background. Use a sine wave remapped from -1..1 into 0..1:

Python
level = (math.sin(pygame.time.get_ticks() / 1000 * 2) + 1) / 2     # 0..1
colour = (int(60 + 195 * level), int(40 + 80 * level), int(120 + 100 * level))
screen.fill(colour)

To blend two colours, use linear interpolation per channel, or Color.lerp:

Python
c = pygame.Color(30, 30, 80).lerp(pygame.Color(255, 140, 60), level)
Python Colour breathing values

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.

Screen shake and flashes

A cheap, powerful effect is shaking the whole view when something heavy happens. Keep a shake value that decays, and offset everything you draw by a random amount proportional to it.

Python
shake = 0.0

def hit():
    global shake
    shake = 12                               # pixels

# in the loop
offset = Vector2(random.uniform(-shake, shake), random.uniform(-shake, shake))
screen.blit(world_surface, offset)           # draw the world to a surface first
shake = max(0, shake - 40 * dt)              # fade out

Rendering the scene to an off-screen world_surface and blitting it with an offset keeps shake code in one place. A white flash works the same way: fill a translucent white surface whose alpha falls from 200 to 0.

Maths art: Rhodonea curves and the Maurer rose

Particle systems are not the only way to dazzle. A rose curve (Rhodonea) is the polar equation r = cos(k * theta). For integer k it draws a flower with k petals when k is odd and 2k petals when k is even. The Maurer rose connects points of the rose that are a fixed number of degrees apart, producing intricate line art.

Python
import math, pygame

def maurer_points(n, d, size):
    pts = []
    for i in range(361):
        k = math.radians(i * d)
        r = size * math.sin(n * k)
        x = r * math.cos(k) + cx
        y = r * math.sin(k) + cy
        pts.append((x, y))
    return pts

pygame.draw.lines(screen, (255, 120, 180), False, maurer_points(6, 71, 180), 1)

Try n=6, d=71 and then n=2, d=29. Plot the first as a rose with d=1 to see the smooth petals; larger d values spread the same points into a web. Animating d slowly gives a hypnotic screensaver.

Python Count the points of a Maurer rose

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.

All curves stay within the radius of 100 pixels, because the sine factor never exceeds 1.

Performance tips

  • Prefer pygame.draw.circle or pre-rendered small surfaces over per-pixel loops.
  • For glows, pre-render a soft circle once and blit it with special_flags=pygame.BLEND_RGB_ADD for a bright additive look.
  • Reuse particle objects from a pool if you create thousands per second.
  • Spawn counts should scale with dt (rate * dt), not with frames.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the normalized age t = life / max_life let you do?

    t runs from 1 to 0, so effects like fading and shrinking are simple functions of it.
  2. 2. Why rebuild the particle list with a comprehension instead of calling remove() inside a for loop?

    Mutating a list during iteration shifts items and causes some to be skipped.
  3. 3. How do you make flakes in snowfall look closer to the camera?

    Larger and faster flakes suggest depth through parallax.
  4. 4. How many petals does the rose r = cos(3 * theta) have?

    For odd k the rose has k petals; even k gives 2k.

Summary

  • A particle has position, velocity, lifetime and appearance; a system spawns, updates, culls and draws them.
  • Normalized age drives fading and shrinking; spawn rates should depend on dt.
  • Snowfall wraps flakes at the screen edge and uses speed and size for depth.
  • Sine waves create colour breathing, and a decaying offset creates screen shake.
  • Polar maths such as Rhodonea curves and the Maurer rose make striking visuals for free.

Next: Game States and Menus