Menu
CoddyTech

원형 히트박스

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

픽셀 검사는 정확하지만, 정확하다고 해서 항상 공정하게 느껴지는 것은 아닙니다. 가시가 날개 끝을 스치기만 해도 충돌로 처리됩니다. 대신 많은 게임은 더 작고 단순한 모양인 충돌 판정 영역으로 검사해 아슬아슬하게 빗나간 경우는 충돌로 처리하지 않습니다.

둥근 물체에는 원으로 검사합니다. 각 스프라이트에 radius를 지정하면 pygame.sprite.collide_circle은 두 반지름을 더한 값보다 중심 간 거리가 가까울 때 충돌로 처리합니다.

self.radius = 24  # Player.__init__에서
self.radius = 22  # Ball.__init__에서

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

이 경우 중심 간 거리는 24 + 22 = 46픽셀입니다. 원은 그림보다 작으므로 가장자리끼리 스쳐도 충돌하지 않을 수 있습니다. 원 검사는 연산 비용도 적습니다. 거리 계산 한 번이면 되고 픽셀은 검사하지 않습니다.

radius가 없으면 collide_circle은 Rect 전체를 둘러싸는 원을 사용하며, 이 원은 Rect 자체보다 큽니다. 상자 모양의 스프라이트에는 더 작은 Rect를 사용해 같은 효과를 얻을 수 있습니다. self.rect.inflate(-16, -16)은 중심은 그대로 두고 너비와 높이를 각각 16픽셀 줄인 Rect입니다.

challenge icon

챌린지

중급
  1. Player에 self.radius = 24를, Ball에 self.radius = 22를 설정하세요.
  2. collide_mask 대신 pygame.sprite.collide_circle로 테스트하세요.

직접 해보기

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))
        self.mask = pygame.mask.from_surface(self.image)

    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))
        self.mask = pygame.mask.from_surface(self.image)


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, pygame.sprite.collide_mask)

    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()
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

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

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