How do I make an object accelerate a chosen amount per real time second, instead of per frame?

Viewed 50

As part of a Pygame physics engine I'm working on, I would like to have it so each particle accelerates by 9.81 pixels per real time second, instead of every single frame, which is the way it currently works:

self.y_acceleration = 9.81
self.y_velocity += self.y_acceleration 
self.y += self.y_velocity * delta_time

I already have use this code to create a timer:

current_time = time.time()
delta_time = current_time - previous_time
previous_time = current_time
timer += delta_time
1 Answers

You need to calculate the motion per frame as a function of the frame rate.

pygame.time.Clock.tick returns the number of milliseconds since the last call. If you call it in the application loop, this is the number of milliseconds that have elapsed since the last frame. Multiply the object speed by the elapsed time per frame to get constant motion regardless of FPS.

Define the distance in pixels that the player should move per second (pixels_per_second) when self.y_velocity is 1. Then calculate the distance per frame in the application loop:

clock = pygame.time.Clock()
pixels_per_second = 500 # 500 pixels/second - just for example

run = True
while run:
    # [...]
    
    delta_time = clock.tick(100)
    pixel_per_frame = pixels_per_second * delta_time / 1000  

    self.y += self.y_velocity * pixel_per_frame

    # [...]
Related