Pygame clock tick stuttering

796 Views Asked by At

This is an issue that has been bugging me for a few weeks now. Whenever I have a pygame clock variable, so for example: clock = pygame.time.clock and I limit the fps using: clock.tick(fps) the game will occasionally stutter. I have a simple example below - a window with a cube that moves from side to side.

import pygame

screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
width, height = screen.get_size()

rect = pygame.Rect(0, height // 2 - 50, 100, 100)

delta_x = 5

clock = pygame.time.Clock()

running = True
while running:
    event = pygame.event.poll()
    if event.type == pygame.QUIT:
        running = False

    screen.fill((0, 0, 0))

    if rect.left < 0 or rect.right > width:
        delta_x *= -1

    pygame.draw.rect(screen, (255, 255, 255), rect)
    rect.x += delta_x

    pygame.display.flip()

    clock.tick(60)

Video: https://www.youtube.com/watch?v=6spFoKIqVQY&ab_channel=NotAHackusator
Does anyone know how to fix this? Thanks in advance.

2

There are 2 best solutions below

0
On BEST ANSWER

Setting clock.tick to 144 from 60 makes the stutter go away from my end. I'm not not sure if you want it to be limited to 60 and why though.

0
On

There actually is something that might help to improve performance (because the stuttering seams to come because of unstable performance. At least in my case it helped to disconnect displaying and computation meaning you cap the FPS using a custom FPS limiter.

Example:

# In your game-loop:
cur_ticks = pygame.time.get_ticks()
if cur_ticks - last_ticks > 1000//60:  # your framerate, also known as FPS, here 60
            # your draw code and display.update goes here
            last_ticks = pygame.time.get_ticks()
clock.tick(60)  # number of computation steps per second, should be greater equal to FPS-value

You need to initialze last_ticks before your game-loop to zero or to the current value of pygame.time.get_ticks().

For my game this improved the FPS from 40 to 50 FPS compared to the usual approach.

It might also help to increase the clock.tick-value to something higher like 120. This way the FPS is still limited to 60, but allows more computation steps. In my case this helped to improve the number of computation steps/second to over 60 also meaning 60 FPS (for displaying). To keep the speed of game-objects "constant" then requires you to change their speeds based on the current FPS-value. The reason why this helps seams to be that tick is very "heavy".