12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class CanvasPositionManager : MonoBehaviour
- {
- private float radius = 1f;//圆的半径
- private int numberOfObjects;//每行排列多少个物体
- private int theChildCount;//需要排列的物体的总个数
- private void Awake()
- {
- if (this.transform.name == "GGKFTherUIP")//这里可以忽略,是我自己的需求,根据不同场景中的物体名字决定一行排列多少个
- {
- numberOfObjects = 5;
- }
- else
- {
- numberOfObjects = 10;
- }
- theChildCount = this.transform.childCount;//物体总个数就是当前物体下的子物体的个数
- GerCurP(this.transform);//排列
- }
- private void Start()
- {
- }
- /// <summary>
- /// 半圆排列
- /// </summary>
- /// <param name="trans"></param>
- public void GerCurP(Transform trans)
- {
- if (theChildCount <= numberOfObjects)//如果总个数小于等于一行的个数,那只需要排列一行
- {
- print("个数不超过十个");
- for (int i = 0; i < trans.childCount; i++)
- {
- float angle = i * Mathf.PI / numberOfObjects;//根据每个物体(i)乘圆周率(Π)
- Vector3 pos = new Vector3(Mathf.Cos(angle), 0, Mathf.Sin(angle)) * radius;
- this.transform.GetChild(i).position = pos;
- }
- }
- else
- {
- print("个数!!!超过十个");
- int temp = trans.childCount / numberOfObjects;//行数(伪行数)
- int tempNumber;//记过下边的if else计算,得出真正所需的行数(真行数)
- float highUp = 0;
- if (temp % numberOfObjects == 0)
- {
- tempNumber = temp;
- }
- else//对10取余不为零,补一行
- {
- tempNumber = temp + 1;
- }
- Debug.Log("总共有几行" + tempNumber);
- //排列思路:(我的每个物体高度是200)第一行排在-200,然后每行依次+200,最后一行排在第一行下边也就是-400,这样开起来比较居中。因为排列太多行会看不清楚内容,所以一般五六行就够了,所以采用比较固(僵)定(硬)的排列方式,可以根据自己需求更改。
- for (int i = 0; i < tempNumber; i++)//循环几列
- {
- if (i == tempNumber - 1)//最后一行Y坐标需要排在第一行的下边(固定值,-400位置)
- {
- for (int j = (numberOfObjects * i); j < trans.childCount; j++)//最后一行的头到最终末尾
- {
- if (j >= (numberOfObjects * i) && j < trans.childCount)
- {
- float angle = (j - (numberOfObjects * i)) * Mathf.PI / numberOfObjects;//每行的每个点占圆周率的比例
- print(angle);
- Vector3 pos = new Vector3(-Mathf.Cos(angle), 0, Mathf.Sin(angle)) * radius;//对angle取余弦和正弦值再乘以半径获得当前物体在的坐标
- this.transform.GetChild(j).position = new Vector3(pos.x, pos.y - 400, pos.z);//坐标赋值
- }
- }
- }
- else
- {
- for (int j = (numberOfObjects * i); j < numberOfObjects * (i + 1); j++)//每行的开头到当前行的末尾
- {
- if (j >= (numberOfObjects * i) && j < numberOfObjects * (i + 1))
- {
- float angle = (j - (numberOfObjects * i)) * Mathf.PI / numberOfObjects;//
- print(angle);
- Vector3 pos = new Vector3(-Mathf.Cos(angle), 0, Mathf.Sin(angle)) * radius;
- this.transform.GetChild(j).position = new Vector3(pos.x, pos.y + highUp - 200, pos.z);
- }
- }
- }
- highUp += 200;
- }
- }
- }
- }
|