/// <summary> /// 在地图的指定位置由预制体创建Tile /// 同时删除原有的Tile /// </summary> /// <param name="cellPos"></param> /// <param name="prefab"></param> public void CreateTileAt(Vector2Int cellPos, E_PrefabTile prefab) { DestroyTileImmediate(cellPos); var tile = E_PrefabTile.Create(prefab).SetMap(this).SetCellPos(cellPos); tileArray2D.SetByCoord(cellPos, tile); }
/// <summary> /// 通过外部空间的坐标设置指定位置的Tile /// 当超出当前空间边界时,进行自动扩容 /// </summary> /// <param name="coord"></param> /// <param name="tile"></param> public void SetByCoord(Vector2Int coord, E_PrefabTile tile) { if (IsOutOfCapacity(coord)) { ExpandCapacity(coord); } var index = CoordToIndex(coord); array[index.x + index.y * capacity.x] = tile; }
/// <summary> /// 每个维度单方向扩容至可以容纳outIndex索引 /// 并保持原有外部坐标不发生变化 /// </summary> /// <param name="outCoord"></param> private void ExpandCapacity(Vector2Int outCoord) { var outIndex = CoordToIndex(outCoord); // 计算扩充后的数组长宽及外部原点 var newOriginIndex = originIndex; var sumIncrement = new Vector2Int(); if (outIndex.x >= capacity.x) { sumIncrement.x = outIndex.x - capacity.x + 1 + increment.x; } else if (outIndex.x < 0) { sumIncrement.x = -outIndex.x + increment.x; newOriginIndex.x += sumIncrement.x; } if (outIndex.y >= capacity.y) { sumIncrement.y = outIndex.y - capacity.y + 1 + increment.y; } else if (outIndex.y < 0) { sumIncrement.y = -outIndex.y + increment.y; newOriginIndex.y += sumIncrement.y; } var newCapacity = capacity + sumIncrement; var newArray = new E_PrefabTile[newCapacity.x * newCapacity.y]; // 转移原有的Tile for (int x = 0; x < newCapacity.x; x++) { for (int y = 0; y < newCapacity.y; y++) { newArray[x + y * newCapacity.x] = GetByCoord(new Vector2Int(x, y) - newOriginIndex); } } // 更新属性 array = newArray; capacity = newCapacity; originIndex = newOriginIndex; }
/// <summary> /// 创建 /// </summary> /// <param name="prefab"></param> /// <returns></returns> public static E_PrefabTile Create(E_PrefabTile prefab) { if (prefab == null) return null; return (E_PrefabTile) PrefabUtility.InstantiatePrefab(prefab); }