简体   繁体   中英

How to make a delay in a keypress in pygame?

I am making a platformer and to make an easy version of gravity, I need to make it so when I jump(spacebar) after 2 seconds or so gravity turns back on. Basically 'ychange' changes the y axis position of the character per frame (if ychange = 3, it goes down 3 pixels per frame). It is always set to 6 so he falls 6 frames per frame until he hits something that has a collision, to make him jump ychange is set to -6 or -7, which makes him raise 6 or 7 pixels a frame.

My question is, how can I delay switching from ychange = -6 to ychange = 6 for a jump

Ex:

WHEN JUMP: ychange = -6 DELAY FOR 2-3 SECONDS ychange = 6

I have obviously tried time.sleep and pygame.time.wait but they literally pause the program until the wait is over which obviously is not good.

The code for the jump is:

while not gameExit:
    for event in pygame.event.get(): # Binds
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_a:
                xchange -= 3
            if event.key == pygame.K_d:
                xchange += 3
            if event.key == pygame.K_SPACE: # SPACEBAR/JUMP
                ychange = -6
                time.sleep(2)
                ychange = 6
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_a or event.key == pygame.K_d:
                xchange = 0

They "if event.key == pygame.K_SPACE" is the jump part, the rest are other binds.

That is an example of it with time.sleep command which pauses the whole program until the delay is finished.

Any ideas?

Restatement:

Problem: Delay pauses the program

Tried: time.sleep, pygame.time.wait

Question: How do I get a delay that will not pause the whole program

use pygame.time.get_ticks() to get the time when the player presses space and then set a boolean flag to true. Then get the time once a frame until 2 seconds have passed from the original time, at which point you set ychange to 6 and set the flag to false again.

Alternatively look up threading like one of the comments suggests.

Pseudocode:

flag = False; # do this before the game loop starts

if event.type == pygame.KEYUP:
    # checking flag prevents resetting the timer
    if flag == False and event.key == pygame.K_w:
        starttime = pygame.time.get_ticks()
        ychange = -6
        flag = True

# wait 2000 milliseconds before executing this 
if flag == True and pygame.time.get_ticks() - starttime >= 2000:
    ychange = 6
    flag = False

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