0

I have been trying to fix this bug where when you press two buttons at the same time and realse one of them the character in pygame doesn't move to the button that's pressed down.

def tank_control(event):
    if event.type == KEYDOWN:
        if event.key == K_UP:
            tanks_list[0].accelerate()
        elif event.key == K_DOWN:
            tanks_list[0].decelerate()
        elif event.key == K_LEFT:
            tanks_list[0].turn_left()
        elif event.key == K_RIGHT:
            tanks_list[0].turn_right()
    elif event.type == KEYUP: 
        if event.key == K_DOWN or event.key == K_UP:
            tanks_list[0].stop_moving()
        if event.key == K_LEFT or event.key == K_RIGHT:
            tanks_list[0].stop_turning()

1 Answers1

0

You could try working with two separate if blocks, instead of all elif. This way you can both accelerate and turn.

def tank_control(event):
    if event.type == KEYDOWN:
        if event.key == K_UP:
            tanks_list[0].accelerate()
        elif event.key == K_DOWN:
            tanks_list[0].decelerate()
        if event.key == K_LEFT:
            tanks_list[0].turn_left()
        elif event.key == K_RIGHT:
            tanks_list[0].turn_right()
    elif event.type == KEYUP: 
        if event.key == K_DOWN or event.key == K_UP:
            tanks_list[0].stop_moving()
        if event.key == K_LEFT or event.key == K_RIGHT:
            tanks_list[0].stop_turning()
Herman
  • 500
  • 7
  • 18
  • Still doesn't work if i press the left key and right key at the same time then releasing one of them, the character just stops moving instead of turning to the key thats pressed down. – mabest amin Nov 18 '21 at 10:08
  • Well so it does work, it's just that you have an additional problem. That's because if you do get an KEYUP event the .stop_moving() function is called. You should also split those up in left and right buttons. Something like .stop_turning_left() / .stop_turning_right() – Herman Nov 18 '21 at 11:05