简体   繁体   English

六边形网格中螺旋坐标和轴坐标之间的转换

[英]Convert between spiral coordinates and axial coordinates in hexagon grid

I'm making a hexagon tile based game, which generates a honeycomb arrangement of hexagons in a spiral shape.我正在制作一个基于六边形瓷砖的游戏,它会生成螺旋形六边形的蜂窝状排列。 My goal is to convert a world position (eg a mouse click) to a spiral coordinate (index / layer / position around layer).我的目标是将世界 position(例如鼠标单击)转换为螺旋坐标(索引/层/position 周围层)。 I can't think of how to do this, so instead I've been looking to simplify the problem by converting to/from axial coordinates first.我想不出该怎么做,所以我一直在寻求通过首先转换为轴坐标或从轴坐标转换来简化问题。 How can this be done?如何才能做到这一点?

My configuration is pointy-topped as follows:我的配置是尖顶的,如下所示:螺旋坐标图层/位置

And here are the spiral indexes:这是螺旋指数:螺旋坐标指数

Axial Coordinates for reference:轴向坐标供参考:

轴向坐标

I already have these equations for spiral coordinates:我已经有了这些螺旋坐标方程:

const Layer = (index: number): number => {
    return Math.floor((3 + Math.sqrt(12 * index - 3)) / 6);
}
const Position = (index: number, layer: number): number => {
    return index - 3 * layer * (layer - 1) - 1;
}
const Index = (layer: number, position: number): number => {
    return 3 * layer * (layer - 1) + 1 + position;
}

You can check the individual cases as follows.您可以按以下方式检查个别情况。 Here L is layer, P is position, (x, y) are the axial coordinates;这里L是layer, P是position, (x, y)是轴向坐标; coordinates are in agreement with your images.坐标与您的图像一致。

From (L, P) to (x, y) :(L, P)(x, y)

if L == 0:
   return (0,0)

otherwise:
k = floor(P/L) mod 6
j = P mod L

k   x     y     z
-------------------
0   j     L-j   -L
1   L     -j    j-L
2   L-j   -L    j
3   -j    j-L   L
4   -L    j     L-j
5   j-L   L     -j

From (x, y) to (L, P) :(x, y)(L, P)

z = -x-y
L = max(abs(x), abs(y), abs(z))

  x    y    z       P
------------------------
>=0  >=0              x
      <0   <0     L - y
>=0       >=0    2L + z
 <0   <0         3L - x
     >=0  >=0    4L + y
 <0        <0    5L - z

Disclaimer: I didn't test this.免责声明:我没有测试这个。

You may also be able to fold some of the cases by exploiting the symmetry, but coding these directly may be easier, albeit a bit more verbose.您也可以通过利用对称性来折叠某些情况,但直接对这些情况进行编码可能会更容易,尽管有点冗长。

You already coded the functions to go between (L, P) and spiral.您已经在(L, P)和螺旋线之间将函数编码为 go。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM