Menu
CoddyTech

Animate with Time

Part of the Sprites and Images section of Coddy's Pygame journey. Lesson 27 of 36.

A frame counter ties the animation to the frame rate. On a computer that only manages 30 frames a second, the bug's wings flap at half speed. Tie it to time instead.

pygame.time.get_ticks() is the number of milliseconds since pygame.init(). Divide by how long each picture should last and you get how many pictures have gone by; % turns that into an index:

frame_index = pygame.time.get_ticks() // 120 % len(frames)

From 0 to 119 ms that is picture 0, from 120 to 239 ms picture 1, then 2, then 0 again. No counter to keep and reset: one line, worked out fresh each frame. If the game slows down, the animation skips a picture rather than slowing with it.

// divides and drops the remainder: 250 // 120 is 2. This sheet's third row holds a flying bug in three poses, columns 6 to 8, already cut into frames.

challenge icon

Challenge

Medium
  1. Remove timer and the counter.
  2. Each frame, set frame_index from pygame.time.get_ticks() so each of the three pictures shows for 120 milliseconds, in order.

Try it yourself

import pygame

pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Flying Bug")
clock = pygame.time.Clock()

sheet = pygame.image.load("assets/sheets/platformer_characters.png").convert_alpha()
frames = []
for col in (6, 7, 8):
    frame = sheet.subsurface((col * 24, 48, 24, 24))
    frames.append(pygame.transform.scale_by(frame, 3))
frame_index = 0
timer = 0

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    timer += 1
    if timer == 10:
        timer = 0
        frame_index = (frame_index + 1) % len(frames)

    screen.fill((20, 22, 40))
    image = frames[frame_index]
    screen.blit(image, image.get_rect(center=(320, 240)))
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

All lessons in Sprites and Images

Practice on your own: Pygame playground