Home > Backend Development > Python Tutorial > How to Achieve Continuous Sprite Movement in Pygame with Key Presses?

How to Achieve Continuous Sprite Movement in Pygame with Key Presses?

DDD
Release: 2024-12-20 02:27:12
Original
233 people have browsed it

How to Achieve Continuous Sprite Movement in Pygame with Key Presses?

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
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template