How do I detect pygame collisions?

天大地大妈咪最大 提交于 2019-12-02 13:07:06

To use pygame's collition detection funcions (like pygame.sprite.spritecollide), your class does not need to be a subclass of pygame's Sprite.

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 a rect attribute, and it should be a Rect (again, technically, it does not need to be a Rect, only "look like" one).

Given a simple class like this:

>>> class Foo():
...   def __init__(self):
...     self.rect=pygame.rect.Rect(100, 100, 100, 100)

we can use pygame.sprite.spritecollide like this:

>>> f=Foo()
>>> g=Foo()

>>> pygame.sprite.spritecollide(f, [g], False)
[<__main__.Foo instance at 0x0000000003C6DF48>]

Also see how the second argument isn't a Group, but a simple List, 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 pass True as the third argument, this would fail, since spritecollide would try to call sprites() and the second argument and kill() 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 the Sprite 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's Rect 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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!