Delta Time
Part of the The Game Loop section of Coddy's Pygame journey. Lesson 21 of 35.
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) / 1000dt 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 += dtCounting 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
EasyThe fuse burns 1 pixel a frame. Make it burn by time.
- Before the loop, set
elapsed = 0anddt = 0. - Replace
clock.tick(60)withdt = clock.tick(60) / 1000. - In the loop, add
dttoelapsed, and set the fuse's width tomax(0, 480 - elapsed * 40).
Press Play: the fuse burns 40 pixels a second, out in 12 seconds. Then Check.
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