user3853755
user3853755

Reputation: 43

How to constantly move the sprite within a class in pygame

I'm aware of using the get_pressed method to test whether any buttons have been pressed down, however I can't get it to work within a class function.

class MainCharacter (pg.sprite.Sprite):
    def __init__(self, pos, direction, images, *groups):
        pg.sprite.Sprite.__init__(self, *groups)
        self.direction = direction
        self.images = images
        self.image = self.images[self.direction]
        self.rect = self.image.get_rect(topleft=pos)


    def get_event(self, event):
            keys = pg.key.get_pressed()
            if keys[pg.K_a]:
                self.direction = "left"
                self.rect.move_ip(-6, 0)
            elif keys[pg.K_d]:
                self.direction = "right"
                self.rect.move_ip(6, 0)
            elif keys[pg.K_w]:
                self.rect.move_ip(0, -6)
                self.direction = "up"
            elif keys[pg.K_s]:
                self.direction = "down"
                self.rect.move_ip(0, 6)
            self.image = self.images[self.direction]

The sprite will still move 6 spaces each time I press a button, and will not fluidly move.

Upvotes: 0

Views: 108

Answers (1)

sloth
sloth

Reputation: 101052

From your code I can only guess that you call get_event only when an (keydown-)event is handled.

Rename get_event to update and call it every frame, like:

while True:
    for e in pygame.event.get():
        if e.type == blablabla
           ...some event handling...

    yoursprite.update()

instead of

while True:
    for e in pygame.event.get():
        if e.type == pygame.KEYDOWN:
            yoursprite.get_event(e)

Upvotes: 1

Related Questions