unity生成六角网格地图:矩形地图以及矩形地图内随机
本文某些概念是参考国外大神的文章去做的,读者可能需要理解其中某些概念才能了解本文的一些做法
参考链接:https://www.redblobgames.com/grids/hexagons/
用到的地块贴图如下:
先放上六角网格地图效果图:
前两个分别是是固定尺寸竖六边形和固定尺寸矩形,后两个是在前面两个的形状下,在里面随机生成。
开始之前需要定义一个结构体,用于建立六边形地图的坐标系,方便以后做距离判断和攻击范围判断,详细坐标系的介绍请查看链接中Coordinate Systems的Cube coordinates部分,后面的描述称之为立方体坐标
public struct CubeCoordinate { public int q; public int r; public int s; public CubeCoordinate(int q, int r, int s) { this.q = q; this.r = r; this.s = s; } public CubeCoordinate CubePositionAdd(CubeCoordinate offset) { return new CubeCoordinate(q + offset.q, r + offset.r, s + offset.s); } }
在结构体中定义CubePositionAdd是为了方便做坐标相加运算。
另外定义一个静态List用于存放坐标偏移量,分别为左下、右下、下、右上、上、左上。
private static readonly List<CubeCoordinate> hexDirectionOffset = new List<CubeCoordinate> { new CubeCoordinate(-1, 0, 1), new CubeCoordinate(1, -1, 0), new CubeCoordinate(0, -1, 1), new CubeCoordinate(1, 0, -1), new CubeCoordinate(0, 1, -1), new CubeCoordinate(-1, 1, 0) };
另外定义两个List用于存放所有地块的立方体坐标和世界坐标。
private List<CubeCoordinate> cubePosList; private List<Vector2> worldPosList;
定义两个float用于存放六边形之间的宽距离和高距离,参考见链接中Geometry的Size and Spacing部分。
private float widthDistance; private float heightDistance; private void InitHexsDistance() { widthDistance = hexSize * 0.75f * 0.01f; heightDistance = Mathf.Sqrt(3f) * hexSize * 0.5f * 0.01f; }
生成固定尺寸竖六边形的函数如下:
private void CreateHexagonalMap() { Queue<CubeCoordinate> cubePosQueue_BFS = new Queue<CubeCoordinate>(); CubeCoordinate currentCubePos; CubeCoordinate nextCubePos; Vector2 currentWorldPos; Vector2 nextWorldPos; cubePosList.Add(new CubeCoordinate(0, 0, 0)); worldPosList.Add(Vector2.zero); cubePosQueue_BFS.Enqueue(cubePosList[0]); Instantiate(landBlockPrefab, worldPosList[0], Quaternion.identity, transform); while (cubePosQueue_BFS.Count > 0) { currentCubePos = cubePosQueue_BFS.Dequeue(); currentWorldPos = worldPosList[cubePosList.IndexOf(currentCubePos)]; for (int j = 0; j < 3; j++) { nextCubePos = currentCubePos.CubePositionAdd(hexDirectionOffset[j]); if (!cubePosList.Contains(nextCubePos) && nextCubePos.q >= -mapSize && nextCubePos.q <= mapSize && nextCubePos.r >= -mapSize * 2 &&