using System.Collections; using System.Collections.Generic; using UnityEngine; using DG.Tweening; public class RotationChart : MonoBehaviour { public int n;//个数 public float spacing = 1;//间距 float c;//周长 float r;//半径 float ang;//每个角的弧度 float distance = 0;//拖动的距离 List<GameObject> list = new List<GameObject>(); List<Transform> sortList = new List<Transform>(); // Start is called before the first frame update void Start() { //计算周长 c = (1 + spacing) * n; //计算半径 r = c / (2 * Mathf.PI); //计算每个角的弧度 ang = 2 * Mathf.PI / n; //创建人 for (int i = 0; i < n; i++) { list.Add(Instantiate(Resources.Load<GameObject>("player/player_" + i), transform)); float x = Mathf.Sin(i * ang) * r; float z = Mathf.Cos(i * ang) * r; list[i].transform.localPosition = new Vector3(x, 0, z); list[i].AddComponent<PlayerMove>(); sortList.Add(list[i].transform); } } public void Move(float dis) { distance += dis; //计算移动的弧度 = 距离/半径 float moveAng = distance / r; //重新计算位置 for (int i = 0; i < list.Count; i++) { float x = Mathf.Sin(i * ang + moveAng) * r; float z = Mathf.Cos(i * ang + moveAng) * r; list[i].transform.localPosition = new Vector3(x, 0, z); } } //惯性,惯性的初速度就是最后一帧移动的距离 public void Inertia(float endspeed) { //注意:距离有正有负,时间没有,所以求时间要用绝对值 //计算时间 = 初速度/衰减速度 float time = Mathf.Abs(endspeed) / 1; DOTween.To((float a) => { Move(a); }, endspeed, 0, time).OnComplete(() => { //惯性结束之后调用对齐 Align(); }); } public void Align() { //找到离相机最近的 //按z排序 sortList.Sort((a, b) => { if (a.localPosition.z < b.localPosition.z) { return 1; } else if(a.localPosition.z == b.localPosition.z) { return 0; } else { return -1; } }); Debug.Log(sortList[0].localPosition.z); float AlignAng = Mathf.Atan(sortList[0].localPosition.x / sortList[0].localPosition.z); float AlignDis = AlignAng * r; //注意:距离有正负,时间没有,所以要用绝对值 //时间 = 距离/ 速度 float time = Mathf.Abs(AlignDis) / 1; DOTween.To((float a) => { Move(a - distance); }, distance, distance - AlignDis, time); } // Update is called once per frame void Update() { } }
标签:轮转,localPosition,C#,float,list,Mathf,sortList,public From: https://www.cnblogs.com/bazi/p/17150085.html