Menu
CoddyTech

픽셀 단위의 정밀 스프라이트

Coddy Pygame 여정의 스프라이트와 이미지 섹션에 포함된 레슨. 36개 중 23번째.

스프라이트도 마스크를 사용할 수 있으며, pygame이 오프셋을 자동으로 처리합니다. 각 스프라이트에 self.mask를 지정하고, __init__에서 한 번만 만드세요.

self.mask = pygame.mask.from_surface(self.image)

그런 다음 spritecollide의 네 번째 인자로 pygame.sprite.collide_mask를 전달하세요.

hits = pygame.sprite.spritecollide(player, balls, False, pygame.sprite.collide_mask)

네 번째 인자는 각 쌍을 검사하는 데 사용할 방법입니다. 이 인자를 지정하지 않으면 Rect를 검사합니다. collide_mask를 사용하면 각 스프라이트의 Rect 위치에 맞춰 배치된 마스크를 검사합니다. groupcollide에도 같은 다섯 번째 인자를 전달할 수 있습니다.

마스크 검사는 Rect 검사보다 비용이 더 들지만, overlap은 두 Rect가 겹치는 부분의 픽셀만 비교하므로 서로 멀리 떨어진 쌍은 빠르게 처리됩니다. 스프라이트가 수십 개 정도라면 비용을 체감하지 못할 것입니다. 스프라이트에 mask가 없으면 collide_mask는 검사할 때마다 이미지에서 마스크를 만들므로, __init__에서 설정하세요.

challenge icon

챌린지

중급
  1. Player와 Ball에 self.image로 만든 self.mask를 부여합니다.
  2. 배의 이미지가 공에 닿아 있는 동안에만 Hit!가 표시되도록 pygame.sprite.collide_mask를 spritecollide에 전달합니다.

직접 해보기

import pygame

pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Spike Field")
clock = pygame.time.Clock()

ship_image = pygame.image.load("assets/images/ship.png").convert_alpha()
ball_image = pygame.image.load("assets/images/spike_ball.png").convert_alpha()
font = pygame.font.Font(None, 40)


class Player(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = ship_image
        self.rect = self.image.get_rect(topleft=(420, 320))

    def update(self):
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT]:
            self.rect.x -= 4
        if keys[pygame.K_RIGHT]:
            self.rect.x += 4
        if keys[pygame.K_UP]:
            self.rect.y -= 4
        if keys[pygame.K_DOWN]:
            self.rect.y += 4


class Ball(pygame.sprite.Sprite):
    def __init__(self, x, y):
        super().__init__()
        self.image = ball_image
        self.rect = self.image.get_rect(center=(x, y))


player = Player()
balls = pygame.sprite.Group(Ball(160, 240), Ball(320, 240), Ball(480, 240))

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    player.update()
    hits = pygame.sprite.spritecollide(player, balls, False)

    screen.fill((20, 22, 40))
    balls.draw(screen)
    screen.blit(player.image, player.rect)
    if hits:
        text = font.render("Hit!", True, (240, 240, 240))
        screen.blit(text, (10, 10))
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

스프라이트와 이미지의 모든 레슨

직접 연습해 보세요: Pygame 플레이그라운드