JinChanChan/Assets/Scripts/Hexagon/HexagonMap.cs

65 lines
1.8 KiB
C#
Raw Normal View History

using UnityEngine;
// 正六边形地图管理器脚本
public class HexagonMap : MonoBehaviour
{
public GameObject hexPrefab;
public int gridWidth = 10;
public int gridHeight = 10;
public float hexRadius = 1f;
void Start()
{
CreateHexagonalGrid();
}
void CreateHexagonalGrid()
{
float hexWidth = 1.5f * hexRadius; // 横向间距
float hexHeight = Mathf.Sqrt(3) * hexRadius; // 纵向间距
for (int row = 0; row < gridHeight; row++)
{
for (int col = 0; col < gridWidth; col++)
{
// 计算位置
float x = col * hexWidth;
float y = row * hexHeight;
// 偏移行
if (col % 2 == 1)
{
y += hexHeight / 2;
}
Vector3 position = new Vector3(x, 0, y);
Instantiate(hexPrefab, position, hexPrefab.transform.rotation, transform);
}
}
}
void GenerateHexagonalMap()
{
float hexWidth = Mathf.Sqrt(3) * hexRadius;
float hexHeight = 2f * hexRadius;
for (int row = 0; row < gridHeight; row++)
{
for (int col = 0; col < gridWidth; col++)
{
// 偏移行,偶数行和奇数行之间水平偏移
float xOffset = col * hexWidth;
float yOffset = row * hexHeight;
// 偶数列行做偏移
if (col % 2 == 1)
{
yOffset += hexHeight / 2;
}
// 计算每个六边形的位置
Vector3 position = new Vector3(xOffset, 0, yOffset);
Instantiate(hexPrefab, position, hexPrefab.transform.rotation, transform);
}
}
}
}