JinChanChan/Assets/Scripts/Hexagon/HexGrid.cs

68 lines
1.8 KiB
C#
Raw Normal View History

using System;
2025-02-10 17:55:21 +08:00
using UnityEngine;
using Random = UnityEngine.Random;
2025-02-10 17:55:21 +08:00
public class HexGrid : MonoBehaviour
{
public int width = 6;
public int height = 6;
public HexCell cellPrefab;
HexMesh hexMesh;
2025-02-10 17:55:21 +08:00
HexCell[] cells;
public Color defaultColor = Color.white;
public Color touchedColor = Color.magenta;
void Awake()
{
hexMesh = GetComponentInChildren<HexMesh>();
2025-02-10 17:55:21 +08:00
cells = new HexCell[height * width];
for (int z = 0, i = 0; z < height; z++)
{
for (int x = 0; x < width; x++)
{
2025-02-10 17:55:21 +08:00
CreateCell(x, z, i++);
}
}
}
private void Start()
{
hexMesh.Triangulate(cells);
}
void CreateCell(int x, int z, int i)
{
2025-02-10 17:55:21 +08:00
Vector3 position;
position.x = (x + z * 0.5f - z / 2) * (HexMetrics.innerRadius * 2f);
2025-02-10 17:55:21 +08:00
position.y = 0f;
position.z = HexMetrics.offset * z;
2025-02-10 17:55:21 +08:00
HexCell cell = cells[i] = Instantiate<HexCell>(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))
{
TouchCell(Input.mousePosition);
}
}
public void TouchCell(Vector3 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);
2025-02-10 17:55:21 +08:00
}
}