2
\$\begingroup\$

I can only move the rectangle every time I push a key down. How would I continuously move my shape when the key is down?

Here's my code:

for event in pygame.event.get():

    if event.type == pygame.QUIT:
        running=False

    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_d:
            lead_x_change += -10 
        if event.key == pygame.K_a:
            lead_x_change += 10
        if event.key == pygame.K_w:
            lead_y_change += -10
        if event.key ==pygame.K_s:
            lead_y_change += 10 

    if event.type == pygame.KEYUP:
        if event.key == pygame.K_a or event.key == pygame.K_d:
            lead_x_change = 0

    rectx += lead_x_change     
    screen.fill(color)
    rect=pygame.Rect(rectx,recty,10,10)
    screen = pygame.display.set_mode(screen_dimensions)
    pygame.display.update()
\$\endgroup\$

2 Answers 2

1
\$\begingroup\$

You want to move your rectangle updating and screen updating code out from the event loop. Your current code doesn't move the rectangle or update the window if no events are generated. This leads to the incorrect behavior. So, instead your game loop should look something like this:

while Run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            Run = False
        ...

    rect.x += velocityX

    screen.fill(Black)

    pygame.display.flip()

Also, you seem the me recreating the window each event. You should call pygame.display.set_mode once before the game starts, and simply fill the surface between frames.

\$\endgroup\$
0
\$\begingroup\$

If you are only pressing and then releasing one key at a time, that logic should work for you. There must be a problem in the update code that you are not showing. (You do have code somewhere to add lead_x_change to the x position every timer tick, don't you?)

However, you're not handling "rollover" properly. Rollover is where the new key-down action is detected before the key-up from the previous keypress. Suppose you are alternating between left(A) and right(D) quickly. You'll often get the sequence of events:

  1. A key down, sets lead_x_change to -10
  2. delay while rectangle moves
  3. D key down, sets lead_x_change to 10
  4. A key up, sets lead_x_change to 0
  5. delay while rectangle is supposed to move, but doesn't
  6. D key up, sets lead_x_change to 0 again

On KEYDOWN, record the last key pressed in a state variable at the same time you set the lead_?_change state variable. Then, on a KEYUP event, only clear the lead_?_change state variable if the key code matches the key code that last set that value.

You have do to that for each group of "mutually exclusive" keys. You have two independent motion axes, x and y, and each will need it's own "last key code" state to make this work.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .