A Particle
Part of the Sound and Game Feel section of Coddy's Pygame journey. Lesson 8 of 23.
Sparks, dust, smoke and confetti are made of particles: many tiny things that fly out, live a short while and vanish. One particle needs only a few numbers: where it is, how far it moves each frame, and how many frames it has left to live. A dictionary holds them:
{"x": 240, "y": 180, "vx": 2, "vy": -3, "life": 30}vx and vy are its velocity: 2 pixels right and 3 up each frame. Keep every particle in one list, and each frame move them all and take one frame off their life:
for p in particles:
p["x"] += p["vx"]
p["y"] += p["vy"]
p["life"] -= 1Draw each particle while its life is above 0, as a small circle:
for p in particles:
if p["life"] > 0:
pygame.draw.circle(screen, (255, 160, 60), (p["x"], p["y"]), 3)A particle has no image and no class. It is cheap, so a game can have hundreds at once.
Challenge
EasyMake the grey emitter at the middle shoot a spark:
- When Space is pressed, append
{"x": 240, "y": 180, "vx": 2, "vy": -3, "life": 30}toparticles. - Each frame, move every particle by its
vxandvy, and lower itslifeby 1. - Draw each particle whose life is above 0 as an orange
(255, 160, 60)circle of radius 3.
Try it yourself
import pygame
pygame.init()
screen = pygame.display.set_mode((480, 360))
pygame.display.set_caption("Sparks")
clock = pygame.time.Clock()
particles = []
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill((30, 30, 46))
pygame.draw.circle(screen, (120, 120, 140), (240, 180), 8)
pygame.display.flip()
clock.tick(60)
pygame.quit()
All lessons in Sound and Game Feel
Practice on your own: Pygame playground