微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

将 sprite 添加到 group 中,它不会与 group 中的任何 sprite 发生碰撞

如何解决将 sprite 添加到 group 中,它不会与 group 中的任何 sprite 发生碰撞

我想在屏幕上制作大约 10 个云,并且我希望新的云不会与组中任何已添加的精灵发生碰撞。我解决了这个问题,但我的解决方案使云很长一段时间。我该如何解决?什么解决方案可以解决这个问题并更快地添加云?

我的代码

class Cloud(pygame.sprite.Sprite):
    duplicate = False
    images = [load_image(f"cloud{i}.png") for i in range(1,5)]

    def __init__(self,group,x=None,y=None,cloud_index=None):
        if cloud_index:
            self.image = Cloud.images[cloud_index]
            self.cloud_index = cloud_index
        else:
            self.image = random.choice(Cloud.images)
            self.cloud_index = Cloud.images.index(self.image)

        self.rect = self.image.get_rect()
        if not x or not y:
            # There is my solution
            while True:
                self.rect.x = self.x = random.randrange(WIDTH - self.rect.w)
                self.rect.y = random.randrange(HEIGHT - self.rect.h)

                if not pygame.sprite.spritecollideany(self,group) or not group.sprites():
                    break
        else:
            self.rect.x = self.x = x
            self.rect.y = y

        self.vel = 60 / FPS
        super(Cloud,self).__init__(group)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。