I have a game where I need an enemy to spawn after every 1350 milliseconds in a path. And the enemies only start coming after I click on the start button.
Time interval code:
sendEnemy = 0
def enemy_object_creation(sprite_list, health):
global sendEnemy
if pygame.time.get_ticks() >= sendEnemy:
foe = Enemy(sprite_list, health)
enemies.add(foe)
sendEnemy += 1350
Now here, when I click on the start button after around 5 secs, a bulk of of enemies come flooding at the beginning and then afterwards they again start coming smoothly. The more time I take to click on the start button, the more enemies spawn together at start. I'm not sure what to do about it.
Help will be appreciated.
In pygame the system time can be obtained by calling pygame.time.get_ticks()
, which returns the number of milliseconds since pygame.init()
was called. See pygame.time
module.
You need to calculate the time when the first enemy will have to spawn, when the start button is clicked.
Specify the sendEnemy
variable in global namespace:
sendEnemy = 0
Set the initial time value, when the button is clicked:
if clicked:
global sendEnemy
current_time = pygame.time.get_ticks()
sendEnemy = current_time
Spawn new enemies if sendEnemy
is greater than 0, but less than the current time:
def enemy_object_creation(sprite_list, health):
global sendEnemy
if 0 < sendEnemy <= pygame.time.get_ticks():
foe = Enemy(sprite_list, health)
enemies.add(foe)
sendEnemy += 1350
If you want to stop enemies from spawning, set sendEnemy = 0
.
Alternatively you can compute the time when the next enemy will have to spawn, depending on the current time. However, this leads to a slight inaccuracy as the code does not run on time, but a few milliseconds later:
def enemy_object_creation(sprite_list, health):
global sendEnemy
current_time = pygame.time.get_ticks()
if sendEnemy <= current_time:
foe = Enemy(sprite_list, health)
enemies.add(foe)
sendEnemy = current_time + 1350