pythonpgzero

Character movement in Pygame Zero


As of right now, my character moves whilst I'm holding my key down.

e.g.

if keyboard.left:
   actor.x -= 5

However, I would like my actor to move in a sort of block-ish fashion e.g. I press my key once and it moves to the left by 5 pixels, regardless of whether I hold it down or not.

How would I do this?


Solution

  • First

    if keyboard.left: 
        move_direction = 'left'
    

    and later

    if move_direction == 'left':
        actor.x -= 5
    

    and don't reset move_direction.


    Eventually it may need to keep only left or right to stop moving left only when you press right but not when you press top or bottom.

    First

    if keyboard.left: 
        move_horizontally = 'left'
    
    if keyboard.right: 
        move_horizontally = 'right'
    

    and later

    if move_horizontally == 'left':
        actor.x -= 5
    if move_horizontally == 'right':
        actor.x += 5