Skip to content

Allow Sprite "sprite-vs-group" collide methods to ignore the calling sprite (it shouldn't hit itself!)  #3193

@celeritydesign

Description

@celeritydesign

I would suggest some of the Sprite "group" collide methods be extended to allow avoiding checking collisions on a sprite with itself, even if the sprite exists within the group being checked against.

My example use-case is that I have four player ships, and a bunch of asteroids, that get added to a group "all_shootable_objects" during init() When I randomly spawn at the start of a level, I use :

if pygame.sprite.spritecollideany(self, all_shootable_objects, pygame.sprite.collide_rect_ratio(2)):
...to test I'm not spawning on top of another object. Obviously this always reports a collision, as my current object is colliding with itself.

My workaround is to temporarily remove the current object from "all_shootable_objects" and then put it back in afterwards.
That seems a bit clunky though, and I think new users would be pretty confused to always get collisions in a similar scenario.

Maybe adding a new arg, "ignore_self" and default it to False to maintain current behaviour,
e.g. spritecollideany(sprite, group, collided = None, ignore_self = False)

Suggested functions that would benefit (not sure if I've missed others):

  • pygame.sprite.spritecollideany()
  • pygame.sprite.spritecollide()

To put it another way, is there any time you would ever want to register a collision against yourself when checking against a group? It seems counter-intuitive to me, so if there are reasons, maybe adding a note to the documentation for new users would be useful?
Eg: “note, if your sprite is in the same group you are checking against, it will report as colliding with itself! You will need to remove it prior to your check to avoid this.”

Am I missing something obvious, or is this worth considering?

Metadata

Metadata

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions