Search code examples
pythonpygamespritecollision-detection

Collision detection in pygame. Error: no attribute 'rect'


New to pygame, writing a little code to try and detect collisions. Here is a small test file I wrote up to demonstrate the error. It instantiates two sprites, and tries to detect collision between them

import pygame

class Box(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
class Circle(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()

box = Box()
circle = Circle()
group = pygame.sprite.Group()
group.add(circle)
pygame.sprite.spritecollideany(box, group)

However this returns an error:

default_sprite_collide_func = sprite.rect.colliderect
                                  ^^^^^^^^^^^
AttributeError: 'Box' object has no attribute 'rect'

I'm not really sure what I should be doing to remedy the situation. How can I detect collision between two sprites in pygame?

NOTE: edited to include proposed solution from an answer. I'm not making a new question since I'm still getting a similar error.


Solution

  • The spritecolllideany function takes as parameters (sprite, group), i.e. the first parameter is a sprite instance and the second parameter is a sprite group (which contains one or more sprite instances).

    In your example code, your are passing classes; it is equivalent to:

    pygame.sprite.spritecollideany(Box, Circle) # passing the class objects, oops!
    

    The error message might be a little confusing but it is giving some good clues about what is going on: it's essentially saying that the Box class has no attribute named rect (if an instance had been passed in, instead of the error saying type object 'Box'..., it would instead say 'Box' object...).

    You'll probably need something more like:

    box = Box() # create an instance
    circle = Circle()
    group = pygame.sprite.Group() # create a group with a sprite in it
    group.add(circle)
    hit = pygame.sprite.spritecollideany(box, group)
    if hit:
      ... # there was a collision...
    

    Note that your subclasses aren't calling the base Sprite class __init__ method, which you probably want to do. Also, your sprite subclasses don't currently do anything - you'll want to make them draw an image, for example.

    I know you mentioned that your sample code is just a trimmed down example, so maybe you're already doing both of these things in your actual code. If not, the chimp example walks you through some of that.