n0tis February 2016

Pygame get name of colided sprite

For my game written in pygame, I need to detect collision.

For this is use pygame.sprite.spritecollide(), which give me a list of the colided sprite. However, their name isn't quite undertandable: here are 2 colided sprite enter image description here

How do I get the real name of the sprite ?

Answers


Chris February 2016

Since it's not clear what your purpose is, the most obvious solution to me would be to just add a name parameter to each sprite. Then after the collision, you can do:

for sprite in pygame.sprite.spritecollide(sprite1, group1):
    print(sprite.name)
    if sprite.name == 'foo':
        # do whatever

For this to work, in your sprite code, you need to define the parameter:

class MySprite(pygame.sprite.Sprite):
    def __init__(self, name):
        # <your other sprite code>
        self.name = name

Then, when you create the sprite, you pass in a name:

sprite1 = MySprite('test sprite')

Post Status

Asked in February 2016
Viewed 2,928 times
Voted 9
Answered 1 times

Search




Leave an answer