1

I am currently creating a game where an event happens every 800 milliseconds in pygame using the following code:

    spawn_event = pg.USEREVENT + 1 
    pg.time.set_timer(spawn_event, 800)

    for event in pg.event.get():
        if event.type == spawn_event and wave == True:
                spawn_enemy = True #if 800ms has passed, set spawn enemy variable to true which will spawn an enemy

The idea behind this is to spawn an enemy sprite every 800 milliseconds while a wave is in progress.

A problem arises when the game is paused however. Within the same while loop for the main game logic, there is a separate smaller while loop that runs if the game is paused.

When i resume the game after pausing in the middle of a wave, the timing seems to change and an enemy is released later than it should be, as though the timing is being reset or altered.

How can i prevent this so that the timing stays the same? Do i need to change how my game pauses?

omnistat
  • 63
  • 5
  • How are you pausing? – DrevanTonder Apr 08 '18 at 23:27
  • @DrevanTonder Like i said, with a while loop inside the main while loop. If the pause button is clicked, the while loop will run until the player resumes. – omnistat Apr 08 '18 at 23:29
  • maybe you should use https://www.pygame.org/docs/ref/time.html#pygame.time.wait – DrevanTonder Apr 08 '18 at 23:30
  • 1
    Use a counter. Just a variable with an integer that starts at 0 and increment it only while the game is unpaused. Use that as your source of truth rather than any time-based API directly. Once the counter grows past `.8 * your_frame_rate`, then reset it to 0 and spawn an enemy. – Blake O'Hare Apr 09 '18 at 01:10
  • Can you confirm that the timing for the enemy spawn is reset? I think this could help me form an answer. – Ethanol Apr 09 '18 at 01:15
  • @Ethanol The timing is based off of an event that occurs every 800ms in the event system. The distance between each sprite and thus time between each event stays constant until paused. When resuming after pause, the distance between the sprites and therefore the timing is longer than usual for the first sprite thats spawned in. Then it goes back to normal. It may be a case of the fact that the event still occurs even when paused, so if you pause immediately before an event and then resume immediately after an event, the timing in effect adds to produce the effect. This is just my theory though – omnistat Apr 09 '18 at 01:24
  • It sounds like you need to incorporate your pause handling into your main event handler and ignore changes to the game state if paused. Otherwise you could track the game time manually instead of using timer events. – import random Apr 09 '18 at 08:12

0 Answers0