I'm currently developing a small game with pygame and I'm having a hard time figuring out a way to check for collisions. I've found this question, but I can't use the pygame.sprite.spritecollide(player, wall_group, True)
because my called player isn't a 'sprite', it's a class that I've created (that uses the functionality of normal shapes (https://www.pygame.org/docs/ref/draw.html)).
If anyone could figure a way that I can detect collisions and explain to me shortly about the difference between 'sprite' and just a normal shape like circle/rectangle I would appreciate it.
To use pygame's collition detection funcions (like
pygame.sprite.spritecollide
), your class does not need to be a subclass of pygame'sSprite
.Thanks to python's duck typing, the actual class does not matter, as long as your class behaves like a
Sprite
. In this context, it just means that your class should have arect
attribute, and it should be aRect
(again, technically, it does not need to be aRect
, only "look like" one).Given a simple class like this:
we can use
pygame.sprite.spritecollide
like this:Also see how the second argument isn't a
Group
, but a simpleList
, but python does not care, since the only thing that matters in this case is that you can iterate over the object. If you would passTrue
as the third argument, this would fail, sincespritecollide
would try to callsprites()
and the second argument andkill()
on the elements inside.Likewise, if you want to e.g. use pixel perfect collision detection, you need a
mask
attribute etc. So you should use theSprite
class anyway since it offers some more stuff like managing groups. Also, everytime you want to store a position or a size, consider using pygame'sRect
class, since it's quite powerfull and it's used/expected in a lot of pygame functions.tl;dr: Use pygame's
Sprite
class. There's probably no good reason for you to not do it, and a bunch of good reason to actually use it.