Search code examples
pygamepygame-clock

How to set a timer for a specific item in pygame


I'm very inexperienced with pygame & python.. I was wacthing a youtube tutorial about making a platform game with pygame. Everything works just as intended except for one thing..

I want to increase my characters jumping height temporarily but i just don't get it to work the way i want it to. I'm able to increase the jumping height but unfortunately not only temporarily, but until the end of that run. Like i said, i'm very very inexperienced and i'd be glad if anyone could tell me a way to fix my problem

The upper part (boost & mega_boost) work just as planned. Whenever the player character hits them, the character is launched upwards for a few seconds. But "super_jump" shouldn't launch the character in the air, it's only supposed to increase the jumping height, for example the normal jumping height is "20" and i want it to be increased to "40" for 5 seconds.

I've been told that my time checker is inside of the power up function and i should place it somewhere else, but i have no idea where to put it. I'd be really gratefull if anyone could help me Here's the part of the Code:

if pow.type == "super_jump":
                self.player.mega_jump_status = 1
                now = pg.time.get_ticks()
                if now - self.player.last_update > 5000:
                    self.player.mega_jump_status = 0

Solution

  • These sort of things are typically split into two phases. The first is when the power-up is enabled. The model is to allow the power-up for some time, it looks like 5000ms from your question code.

    So there needs to be a section when the extra power is turned on, that records the start-time. Then when the power is used, a time-check needs to determine if the power is still active.

    First, let's move that number into a variable-constant, so if you decide to make it longer/shorter it only needs a single change.

    TIME_MEGA_JUMP = 5000  # milliseconds of power-up
    

    When the player hits the power-up item, simply record the time. Note: self.player.mega_jump_time should be initialised to 0 in your player class, otherwise the jump-test will cause an error, because the variable doesn't exist yet.

    if ( <power-up test condition> ):
        player.mega_jump_time = pygame.time.get_ticks()
    

    Then when the player jumps, test the time to see if the power-up is still in effect:

    ...
    elif ( event.type == pygame.KEYUP ):
        time_now = pygame.time.get_ticks()
        ...       
        elif ( keys[pygame.K_SPACE] ):            # Jump
            # Is the player still mega_jumping
            if ( player.mega_jump_time + TIME_MEGA_JUMP > time_now ):
                # TODO: code Me-me-mega-jump
                pass
            else:
                # TODO: code for normal jump
               pass