您可以利用六边形两侧的坡度为60°这一事实.如果到边界矩形中心的y距离小于距离边界矩形外部的x距离乘以60°的切线,则该点位于六边形内部:
def collideHexagon(bounding_rect, position):
px, py = position
if bounding_rect.collidepoint((px, py)):
dx = min(px - bounding_rect.left, bounding_rect.right - px)
dy = abs(py - bounding_rect.centery)
if dy < dx * math.tan(math.radians(60)):
return True
return False
最小示例:
import pygame, math
pygame.init()
screen = pygame.display.set_mode((400, 400))
clock = pygame.time.Clock()
len = 100
sin_len = math.sin(math.radians(60)) * len
cos_len = math.cos(math.radians(60)) * len
pts = [
(len, 0), (len-cos_len, sin_len), (cos_len-len, sin_len),
(-len, 0), (cos_len-len, -sin_len), (len-cos_len, -sin_len)]
pts = [(x + 200, y + 200) for x, y in pts]
tile_heihgt = sin_len * 2
tile_width = len * 2
tiel_rect = pygame.Rect(0, 0, tile_width, tile_heihgt)
tiel_rect.center = (200, 200)
def collideHexagon(bounding_rect, position):
px, py = position
if bounding_rect.collidepoint((px, py)):
dx = min(px - bounding_rect.left, bounding_rect.right - px)
dy = abs(py - bounding_rect.centery)
if dy < dx * math.tan(math.radians(60)):
return True
return False
run = True
while run:
clock.tick(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
color = "white"
if collideHexagon(tiel_rect, pygame.mouse.get_pos()):
color = "red"
screen.fill(0)
pygame.draw.polygon(screen, color, pts)
pygame.display.flip()
pygame.quit()
exit()