簡體   English   中英

Pygame 中的顏色碰撞檢測

[英]Color collision detection in Pygame

Pygame 中是否有一個函數可以在對象與特定顏色碰撞時返回 True?

我很好奇,因為它對於在 Pygame 中制作類似 Paint 的東西非常有用。

您可以使用pygame.mask.from_thresholdColor創建一個Mask ,並使用標准的 pygame 碰撞檢測。

這是我使用黃色創建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()

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM