ajwood
ajwood

Reputation: 19037

pygame inconsistent updating

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()

Upvotes: 1

Views: 671

Answers (2)

alexpinho98
alexpinho98

Reputation: 909

I think you need to use the clock object that pygame.time provides:

c = pygame.time.Clock()

while True:

    dt = c.tick(framerate) # 0 for framerate removes the cap

    ...

    ex_box.update(dt)

and the update method looks like this:

def update(self, miliseconds_passed):

    self.pos[0] += self.spped[0] * dt # Speed must be in pixels_per_millisecond
    self.pos[1] += self.spped[1] * dt

Note:

If you want the speed to be in pixels per second you must do " * dt / 1000." insead of just " * dt".

And if you want to make the speed in m/s if have to set a constant 'pixels per meter' and multiply the speed by dt/1000. * ppm

Upvotes: 0

Radomir Dopieralski
Radomir Dopieralski

Reputation: 2595

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 is 10+render_time.

Fortunately, PyGame comes with a solution to this: the pygame.time.Clock class 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.

Upvotes: 2

Related Questions