Home >Backend Development >Python Tutorial >How Can I Make a Sprite Move Continuously While Holding Down a Key in Pygame?
Controlling Sprite Movement with Key Hold Down
In your current code, the sprite only moves whenever a key is pressed. To make the sprite move continuously when a key is held down, we can utilize the pygame.key.get_pressed() function. This function returns a list of booleans indicating which keys are currently being pressed.
To implement this, modify your code as follows:
while running: setup_background() spriteimg = plumberright screen.blit(spriteimg, (x1, y1)) for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # Check for key presses keys = pygame.key.get_pressed() # Handle key presses for movement if keys[pygame.K_UP]: y1 -= 1 if keys[pygame.K_DOWN]: y1 += 1 if keys[pygame.K_LEFT]: x1 -= 1 y1 += 0 if keys[pygame.K_RIGHT]: x1 += 1 y1 += 0 pygame.display.flip() clock.tick(120)
In this modified code, we first check which keys are currently being pressed using pygame.key.get_pressed(). Then, we handle each key press by updating the x and y coordinates of the sprite accordingly. This will cause the sprite to move continuously as long as the corresponding key is held down.
The above is the detailed content of How Can I Make a Sprite Move Continuously While Holding Down a Key in Pygame?. For more information, please follow other related articles on the PHP Chinese website!