Menu
CoddyTech

Fade and Shrink

Part of the Sound and Game Feel section of Coddy's Pygame journey. Lesson 10 of 23.

A spark that stays the same until it vanishes looks like a dot switched off. Real sparks cool down: they shrink and change colour as they die. You already have the number for that, the particle's life. Work out the size and the colour from it when you draw.

The radius can follow the life directly:

radius = p["life"] // 10 + 1

With 40 frames left that is 5; with 9 or fewer, 1. The + 1 keeps the radius at 1 or more: a circle of radius 0 draws nothing, and the spark would vanish early.

For the colour, pick from a few steps, hot to cold:

if p["life"] > 25:
    color = (255, 220, 80)
elif p["life"] > 10:
    color = (255, 140, 40)
else:
    color = (180, 50, 40)

Test the biggest number first. Written the other way round, life > 10 would catch a life of 30 too, and the yellow branch could never run.

challenge icon

Challenge

Medium

Space makes a ring of 8 sparks, each living 40 frames. Make them cool down as they fly:

  1. Draw each spark with radius life // 10 + 1.
  2. Colour it yellow (255, 220, 80) while its life is above 25, orange (255, 140, 40) while above 10, and dark red (180, 50, 40) after that.

Try it yourself

import pygame

pygame.init()
screen = pygame.display.set_mode((480, 360))
pygame.display.set_caption("Ring of Sparks")
clock = pygame.time.Clock()

DIRECTIONS = [(3, 0), (2, 2), (0, 3), (-2, 2), (-3, 0), (-2, -2), (0, -3), (2, -2)]
particles = []

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
            for vx, vy in DIRECTIONS:
                particles.append({"x": 240, "y": 180, "vx": vx, "vy": vy, "life": 40})

    for p in particles:
        p["x"] += p["vx"]
        p["y"] += p["vy"]
        p["life"] -= 1

    screen.fill((20, 20, 36))
    for p in particles:
        if p["life"] > 0:
            pygame.draw.circle(screen, (255, 220, 80), (p["x"], p["y"]), 4)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

All lessons in Sound and Game Feel

Practice on your own: Pygame playground