Home > Blockchain >  Why does pygame.time.set_timer() stop working when I give it a parameter higher than 16 miliseconds?
Why does pygame.time.set_timer() stop working when I give it a parameter higher than 16 miliseconds?

Time:06-27

I have a custom user event that I have assigned to the variable enemy_fire, and have it set to activate every 100 ms with pygame.time.set_timer(enemy_fire, 100). However, this does not work. I tried setting it to 10 ms: pygame.time.set_timer(enemy_fire, 10) and it worked, and I kept playing with the time parameter until I found the threshold in which it stopped working, and have found that anything higher than 16 ms does not work. I've been reading the documentation, and I'm pretty sure I'm using this function correctly. This seems like odd behavior to me, I'm not really sure why this is happening.

Here is the main part of my code:

import pygame
import gametools
import players
import enemies
from sys import exit



# initilaization
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption('Bullet hell')
clock = pygame.time.Clock()

# Player
player = players.Player()
enemy = enemies.Enemy()

# Background
back_surf = pygame.image.load('sprites/backgrounds/background.png').convert()

enemy_fire = pygame.USEREVENT   1

# main game loop
while True:

    pygame.time.set_timer(enemy_fire, 100)
    # event loop
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()
        if event.type == enemy_fire:
            print('fire')
            enemy.attack(screen)

    # display background
    screen.blit(back_surf, (0, 0))

    player.draw(screen)
    player.update(screen)

    enemy.draw(screen)
    enemy.update()

    enemy.collision(enemy.rect, player.bullets)

    pygame.display.update()
    clock.tick(60)

CodePudding user response:

You have to call pygame.time.set_timer(enemy_fire, 100) before the application loop, but not in the loop. When you call pygame.time.set_timer() in the loop, it will continuously restart and never fire unless you set an interval time faster than the application loop interval. Since the application loop is limited by clock.tick(60), that's about 16 milliseconds (1000/60).

pygame.time.set_timer(enemy_fire, 100)       # <-- INSERT

# main game loop
while True:

    # pygame.time.set_timer(enemy_fire, 100)   <-- DELETE
    
    # event loop
    for event in pygame.event.get():
        # [...]
  • Related