How do I change the speed of my enemy sprite?

Viewed 38

I am a beginner programmer programming a platformer game, and I don't know how to change the speed of the sprite. Can someone help me?

class Enemy(pygame.sprite.Sprite):
    def __init__(self, x, y):
        pygame.sprite.Sprite.__init__(self)
        self.images_right = []
        self.images_left = []
        self.counter = 0
        self.index = 0
        self.direction = -1
        for num in range(1,2):
            img_right = pygame.image.load(f'img/Base pack/Enemies/walk/slimeWalk{num}.png')
            img_right = pygame.transform.scale(img_right, (40, 20))
            img_left = pygame.transform.flip(img_right, True, False)
            self.images_right.append(img_right)
            self.images_left.append(img_left)
        self.image = self.images_right[self.index]
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y

        self.width = self.image.get_width()
        self.height = self.image.get_height()

        self.move_direction = 1
        self.move_counter = 0

    def update (self):
        self.rect.x += self.move_direction
        self.move_counter += 1
        if self.move_counter > 50:
            self.move_direction *= -1
            self.move_counter *= -1
            self.direction *= -1
2 Answers

Just multiply the direction by a speed factor when adding it to the object's position:

class Enemy(pygame.sprite.Sprite):
    def __init__(self, x, y):
        # [...]
        
        self.speed = 5

    def update (self):
        self.rect.x += self.move_direction * self.speed

        # [...]

To decrease the speed of the sprite, I modified my code:

self.heart_beat += 1
if self.heart_beat % 3 == 0:
    self.rect.x += (self.move_direction * self.speed)
    self.move_counter += 1
if self.move_counter > 50:
    self.move_direction *= -1
    self.direction *= -1
    self.move_counter *= -1
Related