1
votes

I'm currently trying to program an space invaders clone. I created an "Invaders"-Class with several attributes and I created an sprite group for all my enemy invaders.

class Invader(pygame.sprite.Sprite):
    def __init__(self, settings, picture, x, y):
        super().__init__()
        self.settings = settings
        self.x = x
        self.y = y
        self.image = pygame.image.load(os.path.join(self.settings.imagepath, picture)).convert_alpha()
        self.image = pygame.transform.scale(self.image, (63,38))
        self.rect = self.image.get_rect()
        self.rect.center = [self.x, self.y]

    def update(self):
        direction_change = False
        print(direction_change)
        if self.rect.x > 800:
            direction_change = True
        else:
            direction_change = False
        if direction_change == False:
            self.rect.x += 1
        if direction_change == True:
            self.rect.x -= 1

With the update function i move the sprite group. But when it moves to a specific point all sprite come together and it looks like this:

My problem

Is there a way to move the group like a single object?

1
why are you setting direction_change = False every frame ? that wouldn't allow your sprites to move at all isn't it ? - user12291970
side note if direction_change: is the same as if direction_change == True: - user12291970

1 Answers

0
votes

The moving direction has to be an attribute of the class Invader. Change the direction if the Sprite is at the left or the right of the window:

class Invader(pygame.sprite.Sprite):
    def __init__(self, settings, picture, x, y):
        super().__init__()
        self.settings = settings
        self.x = x
        self.y = y
        self.image = pygame.image.load(os.path.join(self.settings.imagepath, picture)).convert_alpha()
        self.image = pygame.transform.scale(self.image, (63,38))
        self.rect = self.image.get_rect()
        self.rect.center = [self.x, self.y]

        self.direction = 1 # <---

    def update(self):
        if self.rect.right >= 800:
            self.direction = -1
        if self.rect.left <= 0:
            self.direction = 1
        self.rect.x += self.direction