Menu
CoddyTech

Delta Time

Part of the The Game Loop section of Coddy's Pygame journey. Lesson 18 of 32.

clock.tick(60) does more than wait. It returns how many milliseconds passed since its last call: about 17 at 60 frames a second, more on a slow computer that falls behind. Divide by 1000 and you have dt, the length of a frame in seconds:

dt = 0

while running:
    # events, update, draw, flip
    dt = clock.tick(60) / 1000

dt is 0 in the first frame and the length of the last frame after that. Add it up and you have the time since the game started:

elapsed += dt

Counting frames, as Gem Hunt did, keeps time only while the game runs at a full 60 frames a second. Time measured with dt is right on any computer. The rest of this chapter moves things by time.

challenge icon

Challenge

Easy

The fuse burns 1 pixel a frame. Make it burn by time:

  1. Before the loop, set elapsed = 0 and dt = 0.
  2. Replace clock.tick(60) with dt = clock.tick(60) / 1000.
  3. In the loop, add dt to elapsed, and set the fuse's width to max(0, 480 - elapsed * 40), so it burns 40 pixels a second.

Try it yourself

import pygame

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

width = 480

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

    width = max(0, width - 1)

    screen.fill((30, 30, 46))
    pygame.draw.rect(screen, (255, 150, 40), (0, 170, width, 20))
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

All lessons in The Game Loop

Practice on your own: Pygame playground