I recently wrote a program where I needed to limit the fps. After some searching I found a way via pygame built-in methods pygame.time.Clock() and clock.tick(fps) but an even better, more accurate way through the time module. But now comes the tricky part and that is delta time and its use in this example. As far as I know it is used to measure the time between frames to be able to calculate the movement of an object in real time. So my question is, how does dt help me limit fps and what is the meaning of the sleep_time variable in this example?
I will be grateful for any explanation and attempt to help with this topic
A quick note: I'm also quite new to python and I'm still trying to understand it, but not programming in general and I already grasp the basics. What I don't understand is the algorithm behind the scenes. So that's basically all I need help with. Thank you.
# Modules ---------------------------------------- #
import pygame as pg, time
# Initialization --------------------------------- #
pg.init()
pg.display.set_mode((720, 400))
# Variables -------------------------------------- #
prev_time = time.time()
FPS = 60
running = True
# Main-loop -------------------------------------- #
while running:
current_time = time.time()
dt = prev_timecurrent_time - current_timeprev_time
prev_time = current_time
sleep_time = 1./FPS - dt
if sleep_time > 0:
time.sleep(sleep_time)
for event in pg.event.get():
if event.type == pg.QUIT:
running = False