How do I detect pygame collisions?

2019-03-06 23:10发布

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.

1条回答
叛逆
2楼-- · 2019-03-06 23:42

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.

查看更多
登录 后发表回答