生成3D的正六边形:
public GameObject OBJ;//六边形物体
public int RoundMax = 10;//最大环数变量
public float Radius = 1f;//六边形最短宽度
private Vector3[] Pos_6 = new Vector3[6];//记录6个位置的数组
void Start()
{
Instantiate(OBJ, transform.position, Quaternion.identity);//创建中心物体
for (int round = 1; round <= RoundMax; round++)
{//每一层环的循环体
for (int id = 0; id < 6; id++)
{//放置每一环的顶点物体
Pos_6[id] = new Vector3(Mathf.Sin(60 * id * Mathf.PI / 180) * Radius * round, 0f, Mathf.Cos(60 * id * Mathf.PI / 180) * Radius * round) + transform.position;//记录6个正确位置
Instantiate(OBJ, Pos_6[id], Quaternion.identity);//生成物体
}
if (round > 1)//第2圈开始执行插入
{
for (int id = 0; id < 6; id++)//逐个区间插入物体
{
int NextID = (id + 1) % 6;//获取下一个位置ID,在0~5中循环取值
Vector3 Orientation = Vector3.Normalize(Pos_6[NextID] - Pos_6[id]);//单位朝向(下一个点-当前点)
for (int addID = 1; addID < round; addID++) //循环插入
{
Vector3 Insert_Pos = Orientation * (Radius * addID) + Pos_6[id];//插入点 = 单位方向*当前偏移距离 + 起点偏移
Instantiate(OBJ, Insert_Pos, Quaternion.identity); //生成中间物体
}
}
}
}
}
生成2D正六边形:
public GameObject OBJ;//六边形物体
private int RoundMax = 3;//最大环数变量
private float Radius = 110f;//六边形最短宽度
public Transform parent;
private Vector3[] Pos_6 = new Vector3[6];//记录6个位置的数组
void Start()
{
var go= Instantiate(OBJ, transform.position, Quaternion.identity);//创建中心物体
go.transform.SetParent(parent);
for (int round = 1; round <= RoundMax; round++)
{//每一层环的循环体
for (int id = 0; id < 6; id++)
{//放置每一环的顶点物体
Pos_6[id] = new Vector3(Mathf.Sin(60 * id * Mathf.PI / 180) * Radius * round, Mathf.Cos(60 * id * Mathf.PI / 180) * Radius * round,0f) + transform.position;//记录6个正确位置
var go1 = Instantiate(OBJ, Pos_6[id], Quaternion.identity);//生成物体
go1.transform.SetParent(parent);
}
if (round > 1)//第2圈开始执行插入
{
for (int id = 0; id < 6; id++)//逐个区间插入物体
{
int NextID = (id + 1) % 6;//获取下一个位置ID,在0~5中循环取值
Vector3 Orientation = Vector3.Normalize(Pos_6[NextID] - Pos_6[id]);//单位朝向(下一个点-当前点)
for (int addID = 1; addID < round; addID++) //循环插入
{
Vector3 Insert_Pos = Orientation * (Radius * addID) + Pos_6[id];//插入点 = 单位方向*当前偏移距离 + 起点偏移
var goes= Instantiate(OBJ, Insert_Pos, Quaternion.identity); //生成中间物体
goes.transform.SetParent(parent);
}
}
}
}
}