pythonpygamepygame-surfacepygame-clockpygame-tick

I made velocity changing to make dash but want to add here some dash-lenght limit


so I made my character(player) to change its velocity faster if I press 'L shift' while pressing 'left key' or 'right key' at the same time. The problem is, I wanna make this 'dash' to stop when it reached to the limit I set. I want my character not to dash more than 400 at once. Is there any possible method I can do with..? because I tried many but I still couldn't find anything works. Here's part of my mainloop where the dash is set. char is defined before the loop.

while run:

clock.tick(20)
    
for event in pygame.event.get():
    keys = pygame.key.get_pressed()  
    mods = pygame.key.get_mods() 
    if event.type == pygame.QUIT:
        run = False
    elif keys[pygame.K_LEFT] and mods & pygame.KMOD_LSHIFT or keys[pygame.K_RIGHT] and mods & pygame.KMOD_LSHIFT:
        print("pressed: SHIFT") 
        char.vel = 20
        #I wanna set dash limit to 400px but evry try sitll is all failled..   
    else:
        char.vel = 5

Solution

  • It's fairly easy to use a real-time millisecond limit to a dash. Then you can calibrate the time to however longer you wish the dash to be.

    In the code below I've set this time limit to DASH_TIME_LIMIT. The player char has a new member variable named char.dash_finish. When the dash starts, we put the time limit for the dash in here. Then in the main loop we're checking each frame to see if the current time is after this time, which indicates the time limit has expired.

    To start a dash, first we check that they aren't dashing already. Then the dash_finish time is simply "now" plus some milliseconds in the future.

    DASH_TIME_LIMIT = 700 # milliseconds
        
    for event in pygame.event.get():
        keys = pygame.key.get_pressed()  
        mods = pygame.key.get_mods() 
        if event.type == pygame.QUIT:
            run = False
        elif keys[pygame.K_LEFT] and mods & pygame.KMOD_LSHIFT or keys[pygame.K_RIGHT] and mods & pygame.KMOD_LSHIFT:
            print("pressed: SHIFT") 
            if ( char.dash_finish == None ):   # Not already dashing?
                char.vel = 20
                char.dash_finish = pygame.time.get_ticks() + DASH_TIME_LIMIT
    #    else:
    #        char.vel = 5
    
        # has the dash-time expired?
        time_now = pygame.time.get_ticks()
        if ( char.dash_finish == None ):
            char.vel         = 5
        elif ( time_now > char.dash_finish ):
            # dash has now finished
            char.dash_finish = None
            char.vel         = 5
                    
        clock.tick(20)        
    

    Using a time limit is easier than counting the number of pixels traversed by the player each frame.