简体   繁体   中英

pygame.time.set_timer() event reset?

I've got a little question...

Is there a reset of some sort for the pygame.time.set_timer()?

I've got it running okay but the issue is that I need the timer to reset back to 0 whenever a certain action is performed. As it's running now, the timer will trigger the movedownauto event every second(no matter what happens), but what I want it to do is reset when a key is pressed so that it will then wait one second AFTER the key is pressed to trigger the movedownauto event. It would be ideal if something could be put into the if event.type == USEREVENT: section.

Example below ↓

pygame.time.set_timer(USEREVENT, 1000)

while True:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

        elif event.type == pygame.KEYDOWN:
        # Figure out if it was an arrow key. If so
        # adjust speed.
            if event.key == pygame.K_LEFT:
                x_speed = -40
            elif event.key == pygame.K_RIGHT:
                x_speed = 40
            elif event.key == pygame.K_DOWN:
                y_speed = 40

        # User let up on a key
        elif event.type == pygame.KEYUP:
        # If it is an arrow key, reset vector back to zero
            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                x_speed = 0
            elif event.key == event.key == pygame.K_DOWN:
                y_speed = 0
        # Move the object according to the speed vector.
        x_coord += x_speed
        y_coord += y_speed

        if event.type == USEREVENT:
            movedownauto(screen, x_coord, y_coord)
        else:
            drawcharacter(screen, x_coord, y_coord)



    clock.tick(tickspeed)
    pygame.display.flip()

Thanks!

If you want to trigger the USEREVENT only once after a keypress, remove the pygame.time.set_timer(USEREVENT, 1000) line from the top and add pygame.time.set_timer(USEREVENT, 1000, True) inside the elif event.type == pygame.KEYDOWN: block.

If you set the third argument of pygame.time.set_timer to True , the event will be added to the event queue only once (note that this feature is only avaiable in pygame version 2)

If you want the USEREVENT to happen regulary and just "reset" the timer if a KEYDOWN happens, just remove the timer and add it again.

elif event.type == pygame.KEYDOWN:
    pygame.time.set_timer(USEREVENT, 0)
    pygame.time.set_timer(USEREVENT, 1000)
    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM