前面一章实现了地图的分割,下面来实现点击网格地图的选中状态。当某个网格被选中时,在相应的位置绘制一个mesh,来达到选中的效果。
实现效果图如下:
正方形.png
正六边形.png
1.地图网格控制类(进行了扩展)
public enum GridShapeType
{
///
/// 正方形
///
Square,
///
/// 正六边形
///
RegularHexagon,
}
public class MapGridCtr: MonoBehaviour
{
private const float MAXDIS = 10000001f;
public static MapGridCtr mIns;
///
/// 网格线是否显示
///
public bool showGrid = true;
///
/// 网格线宽度
///
public float gridLine = 0.1f;
///
/// 网格线颜色
///
public Color gridColor = Color.red;
///
/// 网格线
///
private GameObject[,] m_lines;
///
/// 一个网格的基数
///
public int coefficient = 8;
///
/// 当前地图地形
///
public Terrain m_terrian;
///
/// 当前地图地形行数
///
private int m_arrRow = 0;
public int ArrRow
{
get
{
return this.m_arrRow;
}
}
///
/// 当前地图地形宽度
///
private int m_arrCol = 0;
public int ArrCol
{
get
{
return this.m_arrCol;
}
}
///
/// 当前地图vector3数据
///
private Vector3[,] m_array;
public Vector3[,] Array
{
get
{
return this.m_array;
}
}
///
/// 网片
///
private GameObject m_defaultMesh;
private GameObject m_mesh
{
get
{
if (m_defaultMesh == null)
m_defaultMesh = new GameObject();
return m_defaultMesh;
}
}
///
/// 网片形状
///
public GridShapeType m_meshType;
///
/// 网片颜色
///
private Color m_color = Color.yellow;
public Mesh CurrenMesh { get; private set; }
///
/// 网片缓存
///
private Dictionary> meshCaches = new Dictionary>();
protected void Awake()
{
mIns = this;
}
protected void Start()
{
this.LoadMap();
}
///
/// 加载地图数据
///
public void LoadMap()
{
if (this.m_terrian == null)
{
Debug.Log("Terrian is null!");
return;
}
if (this.m_meshType == GridShapeType.Square && this.coefficient < 2)
{
Debug.Log("If the shape of mesh is square, coefficient must be bigger than 2!");
return;
}
TerrainData data = m_terrian.terrainData;
int mapz = (int)(data.size.x / data.heightmapScale.x);
int mapx = (int)(data.size.z / data.heightmapScale.z);
this.m_arrRow = Math.Min(data.heightmapWidth, mapz);
this.m_arrCol = Math.Min(data.heightmapHeight, mapx);
float[,] heightPosArray = data.GetHeights(0, 0, this.m_arrRow, this.m_arrCol);
this.m_array = new Vector3[this.m_arrRow, this.m_arrCol];
for (int i = 0; i < this.m_arrRow; ++i)
{
for (int j = 0; j < this.m_arrCol; ++j)
{
this.m_array[i, j] = new Vector3(j * data.heightmapScale.x, heightPosArray[i, j] * data.heightmapScale.y, i * data.heightmapScale.z);
}
}
if (this.showGrid)
{
this.ShowGrid();
}
}
///
/// 显示地图网格
///
private void ShowGrid()
{
switch (m_meshType)
{
case GridShapeType.Square:
{
this.ShowSquareGird();
break;
}
case GridShapeType.RegularHexagon:
{
this.ShowRegularHexagon();
break;
}
default:
{
Debug.LogError("暂不支持此形状! m_meshType: " + m_meshType);
break;
}
}
}
///
/// 显示正方形网格
/// coefficient代表边的网格数,最小为2
///
private void ShowSquareGird()
{
Vector3[] pos;
int rn = this.m_arrRow / (this.coefficient - 1);
int cn = this.m_arrCol / (this.coefficient - 1);
if (this.m_arrRow % (this.coefficient - 1) > 0)
+&#