Search code examples
pythonpygamegame-physics

Pygame player movement


I have a quick question to ask - why is it so that the rect is still moving even if the key is no longer pressed? (I'm new to pygame, please have patience with me :D) Thank you

import pygame as pg

pg.init()
clock = pg.time.Clock()
clock.tick(30)
HEIGHT, WIDTH = 400, 400


class Clovik(pg.sprite.Sprite):
    def __init__(self):
        pg.sprite.Sprite.__init__(self)
        self.image = pg.Surface((20, 20))
        self.image.fill((162, 38, 0))
        self.rect = self.image.get_rect()
        self.rect.center = ((HEIGHT / 2, WIDTH / 2))

    def update(self):
        keys = pg.key.get_pressed()
        if keys[pg.K_DOWN]:
            self.rect.y += 2




screen = pg.display.set_mode((HEIGHT, WIDTH))
running = True
all_sprites = pg.sprite.Group()
p = Clovik()
all_sprites.add(p)

while running:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            running = False

    all_sprites.update()
    screen.fill((100, 250, 0))
    all_sprites.draw(screen)
    pg.display.flip()

Solution

  • Good question. When you press a key it is "Down" for multiple cycles. You need an event handler. Try an experiment. Replace:

        if keys[pg.K_DOWN]:
            self.rect.y += 2
    

    with:

        if keys[pg.K_DOWN]:
            print("Down")
    

    You'll see that each time you press the Key, multiple prints happen, but stop when you stop pressing down.

    You can either use a variable to keep track of the state of your key (when it changes), or use an event handler.

        for event in pygame.event.get():
            # handle key press
            if event.type == pygame.KEYDOWN: