Continuous Sprite Movement in Pygame with Key Press
In Pygame, sprites typically move only one pixel per key press. To enable constant movement while the key is held down, leverage the pygame.key.get_pressed() function.
The original code below manages sprite movement through individual key presses:
while running: ... if event.key == pygame.K_LEFT: x1 = x1 - 1 y1 = y1 + 0 elif event.key == pygame.K_RIGHT: x1 = x1 + 1 y1 = y1 + 0
To achieve continuous movement, modify the code using pygame.key.get_pressed():
while running: ... keys = pygame.key.get_pressed() # Checking pressed keys if keys[pygame.K_UP]: y1 -= 1 if keys[pygame.K_DOWN]: y1 += 1
In this modified code, keys[pygame.K_UP] and keys[pygame.K_DOWN] check if the up and down keys are pressed respectively. While they are pressed, the sprite moves continuously. Using pygame.key.get_pressed() allows you to handle continuous input, enabling smoother sprite movement in your game.
The above is the detailed content of How to Achieve Continuous Sprite Movement in Pygame with Key Presses?. For more information, please follow other related articles on the PHP Chinese website!