I am trying to understand delta time and wrote this simple example:
import pygame, sys, time
pygame.init()
screen = pygame.display.set_mode((1280,720))
clock = pygame.time.Clock()
rect1 = pygame.Rect(0,150,100,100)
rect2 = pygame.Rect(1180,500,100,100)
speed = 300
last_time = time.time()
while True:
dt = time.time() - last_time
last_time = time.time()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
screen.fill('white')
rect1.x += speed * dt
rect2.x -= speed * dt
pygame.draw.rect(screen,'red',rect1)
pygame.draw.rect(screen,'green',rect2)
pygame.display.update()
clock.tick(60)
The problem I have with it is that the left movement is faster than the right movement. So in the code snippet the green rectangle (rect2) reaches the end of the screen noticeably faster than the red rectangle.
I also tried to use pygame.clock to get delta time:
import pygame, sys, time
pygame.init()
screen = pygame.display.set_mode((1280,720))
clock = pygame.time.Clock()
rect1 = pygame.Rect(0,150,100,100)
rect2 = pygame.Rect(1180,500,100,100)
speed = 300
while True:
dt = clock.tick(60) / 1000
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
screen.fill('white')
rect1.x += speed * dt
rect2.x -= speed * dt
pygame.draw.rect(screen,'red',rect1)
pygame.draw.rect(screen,'green',rect2)
pygame.display.update()
But the result remains the same.
I am really confused by this, am I doing something wrong?
Edit: Someone closed this and linked to deltatime not working at higher framerates. The framerate here is a constant 60fps.