I’m trying to write a simple pygame program where some boxes move around on the screen. I’m following this example.
The tutorial has the following structure:
class Box(pygame.sprite.Sprite):
...
def update(self, currtime):
if self.next_update_time < current_time:
print time.time() # I added this to debug
# Do some stuff
self.next_update_time = current_time + 10
box = Box()
while True:
pygame.time.delay(10)
time = pygame.time.get_ticks()
box.update(time)
My boxes move, but not very smoothly. They speed up and slow down a fair bit. When I plot the points at which an update happens, I get this.
Does this look like a problem with the design proposed in the tutorial I’m following? Is it a problem with my hardware?
EDIT:
Based on Radomir Dopieralski’s answer, the better approach is:
class Box(pygame.sprite.Sprite):
...
def update(self):
# Do some stuff
box = Box()
clock = pygame.time.Clock()
while True:
clock.tick(100)
box.update()
The thing is that
pygame.time.delay(10)will always wait the same time, no matter how long the drawing of the boxes and other things that you do in the game loop took. So the total time waited is10+render_time.Fortunately, PyGame comes with a solution to this: the
pygame.time.Clockclass and it’s.tick(framerate)method, which remembers the time when it was last used and waits a smaller or larger amount of time depending on it, to keep the frame rate constant.