问题描述
我在 Unity 中使用 C# 制作带有六边形网格的游戏。我正在尝试将地图制作成六边形而不是矩形。然而,为了用网格来做到这一点,我需要对矩形网格应用 6 个条件(每边一个),以过滤掉不在我们确定的六边形空间内的瓷砖。例如,使用伪代码:
foreach(tile in rectangle) { if((y <= 2/3*x + 0.5) && (condition2) && ...) { Debug.Log("It's a tile in the hexagon!") } }
我不擅长触发,所以我一直在纠结如何解决这个问题。事实上,我不能得到一个单一的条件来定义六边形的一侧(除了顶部和底部拉伸,这是默认完成的)。任何帮助,将不胜感激。谢谢!
(附加信息:左侧和右侧是 X,相距 0.866;顶部和底部点是 Z,相距 1,但经过拟合,使得一行中的每隔一个图块与其相邻行的距离更近 0.25。)
解决方法
我想通了!我在 desmos 中做了一个完美的六边形:https://www.desmos.com/calculator/8tqplz09tt
然后,我将其转换为代码:
float standardUnitZ = ((mapSize.z * chunkSize.z) - 1f);
float normalUnitZ = standardUnitZ * (13f/15f);
float thisX = ((cz * mapSize.z) + hz);
float sqrt3 = (float)Math.Sqrt(3f);
if (
(theseFinalCoords.z >= (((1 - (13f / 15f)) * normalUnitZ) / 2))//1 BOTTOM
&& (theseFinalCoords.z <= normalUnitZ - (((1 - (13f/15f)) * normalUnitZ) / 2))//2 TOP
&& (theseFinalCoords.z <= sqrt3*thisX + (normalUnitZ / 2f))//3 TOP LEFT
&& (theseFinalCoords.z >= -sqrt3*thisX + (normalUnitZ / 2f))//4 BOTTOM LEFT
&& (theseFinalCoords.z <= -sqrt3*thisX + 2.2320508075f*normalUnitZ)//5 TOP RIGHT
&& (theseFinalCoords.z >= sqrt3*thisX - 1.2320508075*normalUnitZ)//6 BOTTOM RIGHT
)
可能还有一些工作要做,但这是最终结果: