如何在方块世界(Minecraft)中精准生成球体坐标点?
精准生成Minecraft球体范围内的方块坐标点
你目前使用的随机采样算法靠大量随机点覆盖方块,不仅需要极高采样量,还无法做到100%精准覆盖,总会有遗漏:
num_pts = 10000000 indices = arange(0, num_pts, dtype=float) + 0.5 phi = arccos(1 - 2 * indices / num_pts) theta = pi * (1 + 5 ** 0.5) * indices t_x, t_y, t_z = cos(theta) * sin(phi), sin(theta) * sin(phi), cos(phi) tmp = [(g_x0 + int(x * g_radius), g_y0 + int(y * g_radius) + g_radius, g_z0 + int(z * g_radius)) for (x, y, z) in zip(t_x, t_y, t_z)] final_coord_result = list(set(tmp))
半径为5时的生成效果(存在明显遗漏):
要实现100%精准的球体坐标生成,最可靠的方案是遍历所有可能的方块坐标,判断其是否处于球体内,具体实现如下:
核心思路
- 确定遍历范围:以中心点
(x0, y0, z0)为基准,x、y、z轴分别遍历[x0-radius, x0+radius]、[y0-radius, y0+radius]、[z0-radius, z0+radius]内的所有整数坐标 - 用方块中心判断:Minecraft的方块是占据空间的立方体,判断方块中心到球心的距离是否≤半径,能更准确反映方块是否属于球体范围
- 用距离平方比较:避免开根号运算,提升计算效率
Python实现代码
def generate_sphere_coords(x0, y0, z0, radius): sphere_coords = [] radius_squared = radius ** 2 # 遍历所有可能的方块坐标 for x in range(x0 - radius, x0 + radius + 1): for y in range(y0 - radius, y0 + radius + 1): for z in range(z0 - radius, z0 + radius + 1): # 计算方块中心到球心的距离平方 dx = (x + 0.5) - x0 dy = (y + 0.5) - y0 dz = (z + 0.5) - z0 distance_squared = dx**2 + dy**2 + dz**2 # 判断是否在球体内 if distance_squared <= radius_squared: sphere_coords.append((x, y, z)) return sphere_coords # 示例:生成中心点(0,0,0)、半径5的球体坐标 result = generate_sphere_coords(0, 0, 0, 5)
额外说明
- 如果需要生成空心球体,只需在判断条件中加入
distance_squared >= (radius - 1)**2即可 - 该方法效率极高:半径5时仅需遍历1331个点,半径20时也仅需68921个点,Python可瞬间完成计算
- 结果100%精准,不会出现遗漏或多余的方块坐标
内容的提问来源于stack exchange,提问作者Olivier Pons
相关产品推荐
相关产品推荐

