首页 > 解决方案 > 如何知道哪个精灵从组中碰撞?

问题描述

我创建了一个类,这个类的每个成员都是我的精灵组的成员。我测试了我的玩家和小组之间的碰撞:

pygame.sprite.spritecollide(self,surprise_sprites,False)

我想知道我小组中的哪个精灵为了使用他们班级的功能而发生了碰撞。

class Surprise(pygame.sprite.Sprite):
    def __init__(self,x,y,win):
        pygame.sprite.Sprite.__init__(self, sol_sprites)
        pygame.sprite.Sprite.__init__(self, surprise_sprites)
        self.width = TILESIZE
        self.height = TILESIZE
        self.image = Block_surprise
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
        self.y = y
        self.x = x
        self.win = win
        self.exist = True

    def update(self):
        if self.exist:
            self.collision()
        win.blit(self.image,(camera.apply_player([self.rect.x]),self.rect.y))

    def collision(self):
        blocks_hit_list = pygame.sprite.spritecollide(self,player_sprite,False)
        if not (blocks_hit_list == []):
            self.exist = False
            self.image = brick_img
            print("TOUCHE")

    def i_want_to_execute_a_function_here(self):

标签: pythonpygamesprite

解决方案


pygame.sprite.spritecollide()返回碰撞的精灵列表。
可以遍历一个精灵列表:

blocks_hit_list = pygame.sprite.spritecollide(self,surprise_sprites,False)
for hit_sprite in blocks_hit_list:
    # [...] whatever e.g.
    # hit_sprite.myMethod();

推荐阅读