【问题标题】:Color collision detection in PygamePygame 中的颜色碰撞检测
【发布时间】:2020-03-29 13:03:32
【问题描述】:

Pygame 中是否有一个函数在对象与特定颜色碰撞时返回 True?

我很好奇,因为它对于在 Pygame 中制作诸如 Paint 之类的东西非常有用。

【问题讨论】:

    标签: python python-3.x pygame collision-detection


    【解决方案1】:

    您可以使用pygame.mask.from_thresholdColor 创建一个Mask,并使用标准的pygame colision 检测。

    这是我使用 yellow 创建Mask 的示例:

    import pygame
    import random
    
    class Circle(pygame.sprite.Sprite):
        def __init__(self, pos, color, *grps):
            super().__init__(*grps)
            self.image = pygame.Surface((32, 32))
            self.image.set_colorkey((1, 2, 3))
            self.image.fill((1, 2, 3))
            pygame.draw.circle(self.image, pygame.Color(color), (15, 15), 15)
            self.rect = self.image.get_rect(center=pos)
    
    def main():
        screen = pygame.display.set_mode((800, 600))
        colors = ['green', 'yellow', 'white', 'blue']
    
        sprites = pygame.sprite.Group()
        objects = pygame.sprite.Group()
        for _ in range(20):
            pos = random.randint(100, 700), random.randint(100, 600)
            Circle(pos, random.choice(colors), sprites, objects)
    
        for sprite in objects:
            sprite.mask = pygame.mask.from_threshold(sprite.image, pygame.Color('yellow'), (1, 1, 1, 255))
    
        player = Circle(pygame.mouse.get_pos(), 'dodgerblue', sprites)
    
        while True:
            for e in pygame.event.get():
                if e.type == pygame.QUIT: 
                    return
            player.rect.center = pygame.mouse.get_pos()
            if pygame.sprite.spritecollideany(player, objects, pygame.sprite.collide_mask):
                screen.fill((255, 255, 255))
            else:
                screen.fill((30, 30, 30))
            sprites.update()
            sprites.draw(screen)
            pygame.display.flip()
    main()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多