In this guide, we will be creating a PyGame game loop with delta time. Using delta time can be very useful in keeping the movement of your game smoother. Essentially with a delta time based game loop, game objects will appear to move at a constant speed even when the frame rate changes.

Something like the following is common for a PyGame game loop:

while not self.done:

To convert this game loop to utilize delta time, change the above code to the following:

dt = 0
while not self.done:
    dt = self.clock.tick(self.fps) / 1000.0

Then whenever you’re updating the position based on velocity, multiply the velocity by the delta time of the current update. Here’s a quite example of what I mean.

Usually, you could type this to move an object to the right:

self.x += this.speed

With a delta time based game loop, can add a multiplication operation with the delta time.

self.x += this.speed * dt

Of course, you will need to add a delta time parameter to your update method declaration.

def update(self, dt):

So the final example code would look something like:

def update(self, do):
    self.x += self.speed * dot

Hopefully this guide has helped you to create a PyGame game loop with delta time. If it has, you may be interested in the rest of my PyGame tutorial series. To receive news regarding our latest tutorials and courses, you can subscribe to our newsletter. If this tutorial has been valuable, sharing this guide on social media would be highly appreciated.