How to I make the actor jump without stopping the entire code?

Question:

I am attempting to make the dino jump, but when I use time.sleep(0.1) in between the dino jumping and falling, the whole game stops for 0.1 seconds.

I have tried using time.sleep and that’s it as I can’t find any other useful info online.

def jump():
    dino.y -= 100
    time.sleep(0.1)
    dino.y += 100

def on_key_up(key):
    jump()

When I press the up arrow, the entire game freezes for 0.1 seconds.

Asked By: Centr1fuge

||

Answers:

I recommend to use a timer event. When the player jumps, then start a timer by pygame.time.set_timer(). When the timer event occurs, then finish the jump:

jump_delay = 100 # 100 milliseconds == 0.1 seconds
jump_event = pygame.USEREVENT + 1
def jump():
    dino.y -= 100

    # start a timer event which just appear once in 0.1 seconds
    pygame.time.set_timer(jump_event, jump_delay, True)

def on_key_up(key):
    jump()
# event loop
for event in pygame.event.get():

    # jump timer event
    if event.type == jump_event:
       dino.y += 100

# [...]

Note, in pygame customer events can be defined. Each event needs a unique id. The ids for the user events have to start at pygame.USEREVENT. In this case pygame.USEREVENT+1 is the event id for the timer event, which finishes the jump.


Pygame is not Pygame Zero.

Anyway, if you use Pygame Zero, then you can use the elapsed time parameter of the update callback:

def uptate(dt):

The elapsed time parameter (dt) give the time which is passed since the lat frame in seconds.

Create a state (jump) which indicates if the dino is jumping. And a time (jump_time), which states how long the jump has to be continued:

jump = False
jump_time = 0.0

Set the state and the time in jump:

def jump():
    global jump, jump_time
    dino.y -= 100
    jump = True
    jump_time = 0.1 # 0.1 seconds

Decrement the time in update and finish the jump respectively rest the jump state, if the jump_time is less than 0.0:

def uptate(dt):

    if jump:
        jump_time -= dt
        if jump_time < 0:
            dino.y += 100
            jump = False
Answered By: Rabbid76
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.