2
votes

In my pong game, whenever someone scores (the ball goes out to the left or to the right) the ball position is reset to the middle of screen and it waits one second before moving. In that one second I have a little animation going on.

My problem is this: if I pause the game in the middle of the animation, even though none of the objects are updated and only the pause text is drawn, time keeps rolling in. And if I wait time enough, the animation just stops right after I unpause the game. Here's what I mean. This is the ball update:

def update(self, dt):
        now = pygame.time.get_ticks() / 1000
        # if time elapsed since the ball got out >= BALL_WAIT_TIME
        if now - self._spawn_time >= BALL_WAIT_TIME:
            self.rect = self.calcnewpos(dt)
            self.handle_collision()
        # spawn animation
        else:
            step = 255 / (FPS * BALL_WAIT_TIME)
            value = int(self._frame * step)
            rgb = (value, value, value)
            self._draw_ball(rgb)
            self._frame += 1

From http://pygame.org/docs/ref/time.html#pygame.time.get_ticks:

pygame.time.get_ticks()

Return the number of millisconds since pygame.init() was called. Before pygame is initialized this will always be 0.

So even though nothing is drawn or updated while the game is paused, pygame.time.get_ticks() will still return the time elapsed since pygame.init. How can I solve this? Sorry if that is a little hard to understand, I'll post the rest of the code if needed.

1

1 Answers

2
votes

Well it looks as though you're just subtracting the time that some event occurred from the current time. If that's your method for checking how much time has elapsed since the event, then it's not going to matter if the game has been paused. If the event happens and you then pause the game for 10 minutes, it's always going to have been 10 minutes since the event happened.

So with that in mind, you need some way to only count time when the game is active. Perhaps the ball could have an attribute that says how long since the ball got out, and you only increase it if the game isn't paused.

Edit: something like:

class Ball:
    def spawn(self):
        self.sinceSpawn = 0

    def update(self, dt):
        if not gamePaused:
            self.sinceSpawn += dt
        if self.sinceSpawn >= BALL_WAIT_TIME:
            pass #Do something here