Pixels per Second
Part of the The Game Loop section of Coddy's Pygame journey. Lesson 19 of 32.
A speed of 4 pixels a frame is 240 pixels a second only at 60 frames a second. At 30 the same game runs at half speed. Give speeds in pixels per second instead, and multiply by dt to get this frame's step:
speed = 200
if keys[pygame.K_RIGHT]:
x += speed * dtAt 60 frames a second, dt is about 0.017 and the ball moves about 3.4 pixels a frame. At 30, dt is about 0.033 and it moves about 6.7: twice as far each frame, the same 200 pixels each second.
Positions become decimals such as 243.4. That is fine: pygame accepts decimal positions and draws on whole pixels.
Challenge
Easy- Before the loop, set
speed = 200. - Make each arrow move the ball by
speed * dtinstead of 4.
Try it yourself
import pygame
pygame.init()
screen = pygame.display.set_mode((480, 360))
pygame.display.set_caption("Pixels per Second")
clock = pygame.time.Clock()
x, y = 240, 180
dt = 0
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
x -= 4
if keys[pygame.K_RIGHT]:
x += 4
if keys[pygame.K_UP]:
y -= 4
if keys[pygame.K_DOWN]:
y += 4
screen.fill((30, 30, 46))
pygame.draw.circle(screen, (255, 196, 0), (x, y), 16)
pygame.display.flip()
dt = clock.tick(60) / 1000
pygame.quit()
All lessons in The Game Loop
Practice on your own: Pygame playground