Home > Mobile >  Pygame moving multiple sprites not working as expected
Pygame moving multiple sprites not working as expected

Time:09-26

I am making space invaders in pygame, I am relatively new to python and this is my first project in pygame. I am trying to make my aliens move down when reaching the edge of the screen on either side. However, it is not quite working as expected. I am adding a link to a GitHub page so that anyone willing to help can view my code.

Basically what's happening is I have set the aliens to move down 1 pixel when touching the sides because when there are a lot of aliens, this moves them down quite a bit. Obviously, as the aliens start getting killed off, they move down less. However, that is not the strange part. The strange part is the fact that sometimes they will move down 1 px on the one side, but many on the other side. I'm not quite sure what I am doing wrong.

Thanks in advance for any help :)

https://github.com/Kris-Stoltz/space_invaders

CodePudding user response:

I changed that code to

    for alien in aliens:
        if alien.rect.right >= WIDTH-1:
            aliens.update()
        elif alien.rect.left <= 1:
            aliens.update()

But I see if enemies too less they don't move down

def update(self):
    print("x",self.rect.y)
    self.rect.y  = 1
    print("y",self.rect.y)
    self.direction *= -1
That peace of code looks like incorrect

CodePudding user response:

Add break statements so you don't call update multiple times (if an even number of aliens hit the wall, you end up traveling the same direction!) You have to increase the y advance in update too:

for alien in aliens:
    if alien.rect.right >= WIDTH:
        aliens.update()
        break
    elif alien.rect.left <= 0:
        aliens.update()
        break

and:

def update(self):
    self.direction *= -1
    self.rect.y  = 10

The code looks pretty cool though!

  • Related