【发布时间】:2014-11-01 16:03:55
【问题描述】:
我正在使用以下过程为给定范围(左下 --> 右上)的方形网格计算给定半径的六边形多边形坐标:
def calc_polygons(startx, starty, endx, endy, radius):
sl = (2 * radius) * math.tan(math.pi / 6)
# calculate coordinates of the hexagon points
p = sl * 0.5
b = sl * math.cos(math.radians(30))
w = b * 2
h = 2 * sl
origx = startx
origy = starty
# offsets for moving along and up rows
xoffset = b
yoffset = 3 * p
polygons = []
row = 1
counter = 0
while starty < endy:
if row % 2 == 0:
startx = origx + xoffset
else:
startx = origx
while startx < endx:
p1x = startx
p1y = starty + p
p2x = startx
p2y = starty + (3 * p)
p3x = startx + b
p3y = starty + h
p4x = startx + w
p4y = starty + (3 * p)
p5x = startx + w
p5y = starty + p
p6x = startx + b
p6y = starty
poly = [
(p1x, p1y),
(p2x, p2y),
(p3x, p3y),
(p4x, p4y),
(p5x, p5y),
(p6x, p6y),
(p1x, p1y)]
polygons.append(poly)
counter += 1
startx += w
starty += yoffset
row += 1
return polygons
这对于数百万个多边形效果很好,但对于大型网格会很快变慢(并占用大量内存)。我想知道是否有办法对此进行优化,可能通过将根据范围计算的顶点的 numpy 数组压缩在一起,并完全删除循环——但是,我的几何形状还不够好,所以有什么建议欢迎改进。
【问题讨论】:
-
这应该迁移到codereview。
-
其实这是一个关于六角网格的很好的问题。列表中多边形的排序与您相关吗?
-
@MariaZverina 不一定,不。
-
Urschrei,您是否有兴趣找到一个包含特定 P(x,y) 的包含特定 P(x,y) 的网格的封闭六边形,而无需提前计算整个网格?再问大家,有没有既定的方法呢?提前谢谢你
-
@gboffi 不,我正在计算网格以执行一些空间操作——这不是游戏开发问题;这可能对您有用:redblobgames.com/grids/hexagons/#pixel-to-hex
标签: python numpy geometry computational-geometry hexagonal-tiles