조수민
조수민

Reputation: 27

Changing movement speed when multiple keys are pressed

I'm trying to make a simple shooting game with a pygame, but I'm curious. Pressing the direction key made the shape move. Here, if you press the right direction key first and the left direction key, how can you move to the right at a lower speed than the right direction key? here is my origin code

while True:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()       
    pressed=pygame.key.get_pressed()
    if pressed[pygame.K_LEFT]:
        player_left=1
        pos_x -=6
        if player_left==1 and pressed[pygame.K_RIGHT]:
            player_left=0
            pos_x-=3  

Upvotes: 1

Views: 173

Answers (1)

Rabbid76
Rabbid76

Reputation: 211116

Add a states, for the last direction key that was pressed (last_direction_key). Set the states in the KEYDOWN event (see pygame.event module). If only LEFT is pressed, then move to the left. If only RIGHT is pressed, then move to the right. If both LEFT and RIGHT is pressed, the move slowly in the direction which was not pressed last, dependent on the state of last_direction_key:

last_direction_key = None

while True:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        if event.type == pygame.KEYDOWN:
            if pressed[pygame.K_LEFT] or pressed[pygame.K_RIGHT]:
                last_direction_key = event.key

    pressed=pygame.key.get_pressed()
    if pressed[pygame.K_LEFT] and pressed[pygame.K_RIGHT]:
        if last_direction_key == pygame.K_LEFT:
            pos_x += 3
        else:
            pos_x -= 3
    elif pressed[pygame.K_LEFT]:
        pos_x -= 6
    elif pressed[pygame.K_RIGHT]:
        pos_x += 6

Upvotes: 1

Related Questions