Spawning Object issue

2019-08-29 03:43发布

问题:

I am trying to get objects spawn on screen. But they don't seem to come up.

When exiting the game the sprites come up. It's only during the game you can't see any objects.

Exit = False 


while not Exit:
    clock.tick(60)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

            if event.type == QUIT:
            Exit = True

        elif event.type == USEREVENT +1:
            fireball.add(fire(screen, random.randint(50,1000), random.randint(50,800)))

    fireball.update()
    fireball.draw(screen)


    pygame.display.flip()

回答1:

Since you do not tell us, I'm going to assume that fireball is a sprite.Group and fire a child class of sprite.Sprite. From the little I can see, seems to be the correct guess.
So what you want is to create and add fire instances to the fireball group during the game.

You can achieve it by adding the following lines in the main loop before firefall.update():

newev = pygame.event.Event(USEREVENT+1)
pygame.event.post(newev)

This will create a custom event of type USEREVENT+1 which will be catch by the event checking loop next iteration, executing hence the line: fireball.add(fire(screen, random.randint(50,1000), random.randint(50,800)))

Maybe you do not want to create a new fire sprite each iteration. In that case you should add some flow control to skip those lines under some conditions.

For example, if you want a random approach, you can do:

if random.random() < 0.1:
    newev = pygame.event.Event(USEREVENT+1)
    pygame.event.post(newev)

In this case, each iteration of the main loop you have a 10% of probability to submit the custom event. Adjust the probability to your suits.

If instead you want to add a new fire sprite after a given amount of time, you need to measure the time with pygame.time.get_ticks(). If a given amount of time is passed, the event is submitted.

checktime = pygame.time.get_ticks() - reftime
if checktime > 5000: #5 seconds, the time is in milliseconds
    reftime = pygame.time.get_ticks() #reset the reference time
    newev = pygame.event.Event(USEREVENT+1)
    pygame.event.post(newev)

And of course remember to define reftime = pygame.time.get_ticks() the first time before the main loop. You can refer to this answer for another example on how to measure time with pygame.



标签: python pygame