Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

My sprite continues to keep moving even after releasing the key in pygame

My sprite continues to keep moving even after releasing the key. How can I stop the sprite from moving when I release an arrow key?

This is my Paddle sprite class. Here I gave the paddle a speed and the speed should be added to the sprite when the key is pressed.

#Paddle sprite
class Paddle(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((90,20))
        self.image.fill(white)
        self.rect = self.image.get_rect()
        self.rect.centerx = (width//2)
        self.rect.bottom = height-15
        self.speedx = 0
     def update(self):
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT]:
            self.speedx = -5
        if keys[pygame.K_RIGHT]:
            self.speedx = 5
        self.rect.x+=self.speedx

I added all the sprites to a sprite group

#All elements of the game
all_sprites = pygame.sprite.Group()
paddle = Paddle()
all_sprites.add(paddle)

This is the mainloop. I think there's some kind of looping the addition of speed to the sprite but I can't find it.

#Game mainloop
run=True
while run:
    #FPS of gameplay
    clock.tick(fps)

    #Event mainloop
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
           run=False

    #Updating all objects in the game
    all_sprites.update()

    #On screen
    wn.fill(black)
    all_sprites.draw(wn)

    pygame.display.flip()

pygame.quit()
run=True
while run:

    #Event mainloop
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
           run=False

    #Updating all objects in the game
    all_sprites.update()

    #On screen
    wn.fill(black)
    all_sprites.draw(wn)

    pygame.display.flip()

    pygame.quit()
like image 581
MF8 Avatar asked Oct 15 '22 09:10

MF8


1 Answers

You've to reset the speed (self.speedx), if neither LEFT nor RIGHT is pressed:

class Paddle(pygame.sprite.Sprite):

    # [...]

    def update(self):
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT]:
            self.speedx = -5
        if keys[pygame.K_RIGHT]:
            self.speedx = 5

        if not keys[pygame.K_LEFT] and not keys[pygame.K_RIGHT]:
            self.speedx = 0

        self.rect.x+=self.speedx  

Because on each update call, the position still gets updated, and since the speed doesn't get reset, it keeps moving in the direction that it had set before.


Alternatively the speed can be set 0, at the begin of update:

class Paddle(pygame.sprite.Sprite):

    # [...]

    def update(self):

        self.speedx = 0

        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT]:
            self.speedx = -5
        if keys[pygame.K_RIGHT]:
            self.speedx = 5

        self.rect.x+=self.speedx 
like image 142
Rabbid76 Avatar answered Oct 19 '22 06:10

Rabbid76