1

I have a spritegroup. When a member of the spritegroup has a collision, I want to know the rect's position. Here I got the error message 'Group' object has no attribute 'x'

class Landschaft(pygame.sprite.Sprite):       
    def __init__(self,image):
        pygame.sprite.Sprite.__init__(self) 
        self.image = image       
        self.rect = self.image.get_rect()            
        self.rect.x = random.randrange(60, breite -60)
        self.rect.y = random.randrange(100, hoehe - 200) 
        self.rect.center = ( self.rect.x,self.rect.y)

land = pygame.sprite.Group()

for i in range(5):
      image = gegend[i]     
      m = Landschaft(image)        
      hits = pygame.sprite.spritecollide(m,land,True)
        
      if hits:
          i-=1
          print(land.rect.x) 

      land.add(m)
The_spider
  • 1,202
  • 1
  • 8
  • 18
Joachim
  • 375
  • 1
  • 12

1 Answers1

1

A Group has no rectangle and position. Only the items in the Group have a .rect attribute.
pygame.sprite.spritecollide returns a list of sprites.
Furthermore you need to pass False to the doKill argument of spritecollide. If the parameter is True, all Sprites that collide will be removed from the Group.

You have to pass False to doKill:

hits = pygame.sprite.spritecollide(m, land, False)
for hit_sprite in hits:        
    i-=1
    print(hit_sprite.rect.x) 

Also see How do I detect collision in pygame?

Rabbid76
  • 202,892
  • 27
  • 131
  • 174