生成稳定六角形网格的问题

问题描述 投票:0回答:1

enter image description here

我几周来一直在尝试解决问题。我想创建一个六边形网格。最初,我从 Pygame 开始,现在我正在尝试使用 Pyglet。不幸的是,我无法使用这两个库创建精确的网格。

在下面的示例中,我只是为了演示目的而移动该网格。然而,我注意到六边形的形状并不一致;它们在不断地转变和变化。在 Pygame 中,这个问题更加明显,我一直无法找到解决方案。

这是我一直在使用的代码片段:

import pyglet
from pyglet import shapes

window = pyglet.window.Window(1500, 1000)
batch = pyglet.graphics.Batch()

def calc_points(size: tuple[int,int], coord: tuple[int,int]=(0,0)) -> list[tuple[float,float]]:
    b, a = size
    a, b = 1/4*a, 1/2*b
    
    x0, y0 = coord

    x1, y1 = x0+b, y0+a
    x2, y2 = x1+b, y1+a
    y3     =       y2+a
    y4     =       y3+a
    
    return [
        (x0, y1),
        (x1, y0),
        (x2, y1),
        (x2, y3),
        (x1, y4),
        (x0, y3),
        (x0, y1)
    ]

def hex_mul(size: tuple[float,float], pos: tuple[float,float]) -> tuple[float,float]:
    """given size of hexagon and position in hexagon grid, outputs real coord"""
    x, y = pos
    b, a = size
    a, b = 1/2*a, 1/2*b

    coord = (x * 2 * b + y % 2 * b,
             y * 3 / 2 * a )

    return coord

from math import sqrt

size = 20.0
border = 2.0

size = (sqrt(3)/2*size,size)
border = (sqrt(3)/2*border,border)

reduced_size = (size[0] - border[0], size[1] - border[1])

hexagons = []
p = calc_points(reduced_size)

for y in range(200):
    for x in range(200):
        coord = hex_mul(size, (x,y))
        r_coord = (coord[0] + border[0] / 2, coord[1] + border[1] / 2)

        shape = shapes.Polygon(*p, color=(180,170,160,255), batch=batch)
        shape.position = r_coord
        hexagons.append(
            shape
        )

@window.event
def on_draw():
    for s in hexagons:
        x, y = s.position
        s.position = (x+0.8, y+0.7)
    window.clear()
    batch.draw()

pyglet.app.run()
  1. 调整 Pygame 和 Pyglet 中六角网格生成的参数。
  2. 尝试各种渲染和更新技术。

预期结果:

我希望创建一个稳定的六边形网格,它保持一致,并且在移动过程中不会扭曲或移动,或者六边形之间存在持续的间隙。然而,尽管我尝试过,但我仍无法使用 Pygame 或 Pyglet 达到所需的稳定性。

(如果可能的话我宁愿使用pygame,因为我已经习惯了。)

python pyglet hexagonal-tiles
1个回答
0
投票

六边形看起来不稳定的一个可能原因是您使用“真实”

sqrt(3)
来确定它们的大小。这是一个无理数(或者至少是最接近 1 的
float
近似值),因此每个六边形相对于屏幕上的像素将具有不同的偏移量。如果选择有理近似,您可能会得到更好的结果,这样许多六边形都落在相同的子像素偏移上。

尝试这样的事情:

size = 20.0
border = 2.0

sqrt3_approx = 1.75  # try out different approximations to see what looks best

size = (sqrt3_approx/2*size,size)
border = (sqrt3_approx/2*border,border)
© www.soinside.com 2019 - 2024. All rights reserved.