using System;
using UnityEngine;
using Random = UnityEngine.Random;
public class HexGrid : MonoBehaviour
{
///
/// 格子宽度
///
public int width = 6;
///
/// 格子高度
///
public int height = 6;
///
/// 格子实例预制体(用于实际角色放入交互,也有可能会删掉改用判断位置的方式处理交互)
///
public HexCell cellPrefab;
///
/// 六边形渲染mesh
///
HexMesh hexMesh;
///
/// 格子存储
///
HexCell[] cells;
public Color defaultColor = Color.white;
public Color touchedColor = Color.magenta;
void Awake()
{
hexMesh = GetComponentInChildren();
cells = new HexCell[height * width];
for (int z = 0, i = 0; z < height; z++)
{
for (int x = 0; x < width; x++)
{
CreateCell(x, z, i++);
}
}
}
private void Start()
{
// 渲染mesh
hexMesh.Triangulate(cells);
}
///
/// 创建格子以及实例
///
///
///
///
void CreateCell(int x, int z, int i)
{
Vector3 position;
position.x = (x + z * 0.5f - z / 2) * (HexMetrics.innerRadius * 2f);
position.y = 0f;
position.z = HexMetrics.offset * z;
HexCell cell = cells[i] = Instantiate(cellPrefab);
cell.transform.SetParent(transform, false);
cell.transform.localPosition = position;
cell.coordinates = HexCoordinates.FromOffsetCoordinates(x, z);
cell.color = new Color(Random.Range(0, 1f), Random.Range(0, 1f), Random.Range(0, 1f), 1);
}
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
HandleInput();
}
}
///
/// 射线检测拿到射线点,然后传递给TouchCell进行实际位置判断
///
void HandleInput()
{
Ray inputRay = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(inputRay, out hit))
{
TouchCell(hit.point);
}
}
///
/// 判断点击的哪个格子
///
///
public void TouchCell(Vector3 position)
{
// 将 position 从世界空间变换到本地空间
position = transform.InverseTransformPoint(position);
HexCoordinates coordinates = HexCoordinates.FromPosition(position);
int index = coordinates.X + coordinates.Z * width + coordinates.Z / 2;
HexCell cell = cells[index];
cell.color = touchedColor;
hexMesh.Triangulate(cells);
}
}