0
list_zombies = pygame.sprite.Group()
walls = pygame.sprite.Group()

class Zombie(pygame.sprite.Sprite):
    def __init__(self, x, y, speed):
        pygame.sprite.Sprite.__init__(self, list_zombies)
        self.x = x
        self.y = y
        self.speed = zombie_speed
        self.image = pygame.image.load("Zombie.png").convert()
        self.rect = self.image.get_rect()
        self.pos1 = self.x
        self.pos2 = self.y

    def update(self):
        self.y += zombie_speed

    def main(self, display):
        self.update()
        display.blit(zombie_image_copy, (self.x, self.y))

class Wall(pygame.sprite.Sprite):
    def __init__(self, x, y):
        pygame.sprite.Sprite.__init__(self, walls)
        self.x = x
        self.y = y

        self.image = wall_image.convert()
        self.rect = self.image.get_rect()

    def main(display):

        display.blit(wall_image, (-100, 950))

main loop:


for zombie in list_zombies:
        zombie.rect.topleft = (zombie.x, zombie.y)

        if pygame.sprite.groupcollide(list_zombies, walls, 0, 0, collided= None):
            zombie.kill()

These are my classes and i want to kill the zombie if it hits the wall. I have used groupcollide since spritecollide wouldn't work and I would get the error that Wall doesn't have the attribute rect. Somehow it is not working but also not giving me an error. Maybe you can help me.

1 Answers1

0

See How do I detect collision in pygame? and read the documentation! pygame.sprite.Group.draw() and pygame.sprite.Group.update() are methods which are provided by pygame.sprite.Group.

The latter delegates to the update method of the contained pygame.sprite.Sprites — you have to implement the method. See pygame.sprite.Group.update():

Calls the update() method on all Sprites in the Group. [...]

The former uses the image and rect attributes of the contained pygame.sprite.Sprites to draw the objects — you have to ensure that the pygame.sprite.Sprites have the required attributes. See pygame.sprite.Group.draw():

Draws the contained Sprites to the Surface argument. This uses the Sprite.image attribute for the source surface, and Sprite.rect. [...]

The rect attribute is also used for collision detection functions like pygame.sprite.groupcollide. You don't need the .x and .y attributes at all. If you use the .rect attribute (.rect.x and .rect.y) insterad, collision detection works immediately.

If you want to store sprite positions with floating point accuracy, you have to store the location of the object in separate attributes. Synchronize the pygame.Rect object when the position of the object is changed in the update method:

def update(self):
    
    self.x = # change
    self.y = # change

    self.rect.topleft = round(self.x), round(self.y)
Rabbid76
  • 202,892
  • 27
  • 131
  • 174