'framerate independent movement breaking at higher fps?
I am trying to understand framerate independence and wrote this test code: import pygame, sys, time
pygame.init()
screen = pygame.display.set_mode((1280,720))
clock = pygame.time.Clock()
framerate = 60
test_rect = pygame.Rect(0,340,40,40)
move_speed = 300
prev_time = time.time()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
screen.fill('white')
dt = time.time() - prev_time
prev_time = time.time()
test_rect.x += move_speed * dt
pygame.draw.rect(screen,'red',test_rect)
pygame.display.flip()
clock.tick(framerate)
This works but only until about a framerate of 120. Once the framerate goes higher the movement slows down or speeds up. At very high framerates (500+) it often stops as well.
I followed a few different youtube tutorials and they all limit the framerate to 60fps, which seems somewhat hacky. Is there a way to make this work at any framerate?
Solution 1:[1]
tick()
already returns how many milliseconds have passed since the last call. So there is no need to use time
:
clock = pygame.time.Clock()
while True:
dt = clock.tick(framerate) / 1000
# [...]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Rabbid76 |