注意:Main Camera 需要挂载Physics RayCaster
Hierarchy中添加UI里面的EventSystem对象(用来相应拖拽事件)
using DG.Tweening;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using System.Linq;
public class Rotate3D : MonoBehaviour, IDragHandler, IEndDragHandler
{
//生成的数量
int count = 5;
//半径
public int r = 3;
//需要旋转的弧度
float movehu = 0;
//对象集合
List<GameObject> gameObjects = new List<GameObject>();
//排序集合
List<Transform> transforms = new List<Transform>();
//每个角的弧度
float hu;
// Start is called before the first frame update
void Start()
{
hu = 2 * Mathf.PI / count;
//初始化加载每个预制体到对应位置
CreateCube();
//默认加载第一个
ChoseNumber(0);
}
private void HandleDragUpdated(float offset)
{
movehu = offset;
CreateCube();
}
//指定去某个位置
private void ChoseNumber(int n)
{
transforms = transforms.OrderBy(x => x.position.z).ToList();
int index = gameObjects.IndexOf(transforms[0].gameObject);
int next = index - n;
int anext = count - Mathf.Abs(next);
anext = next < 0 ? anext : -anext;
float nextMove = (Mathf.Abs(next) < Mathf.Abs(anext) ? next : anext) * hu;
float nextAng = Mathf.Asin(transforms[0].position.x / r) + nextMove;
DT.To((c) =>
{
movehu = c;
CreateCube();
}, movehu, movehu + nextAng, Mathf.Abs(nextAng));
}
private void CreateCube()
{
for (int i = 0; i < count; i++)
{
if (gameObjects.Count <= i)
{
//加载需要加载的预制体
GameObject obj = GameObject.Instantiate(Resources.Load<GameObject>("player/player_" + i), transform);
obj.transform.Rotate(Vector3.up * 180);
gameObjects.Add(obj);
transforms.Add(gameObjects[i].transform);
}
float x = Mathf.Sin(hu * i + movehu) * r;
float y = Mathf.Cos(hu * i + movehu) * r;
gameObjects[i].transform.position = new Vector3(x, 0, y);
}
}
public void OnDrag(PointerEventData eventData)
{
var dis = eventData.delta.x / (r * 100);
movehu -= dis;//控制方向
CreateCube();
}
public void OnEndDrag(PointerEventData eventData)
{
var dis = eventData.delta.x / 100;
DT.To((a) =>
{
movehu -= a / r;
CreateCube();
}, dis, 0, Mathf.Abs(dis / r)).OnComplete(() =>
{
transforms = transforms.OrderBy(x => x.position.z).ToList();
float zhenghu = Mathf.Asin(transforms[0].position.x / r);
DT.To((b) =>
{
movehu = b;
CreateCube();
}, movehu, movehu + zhenghu, 1);
});
}
}
DO.To() 方法参考我作品中的Unity手写模拟DoTween中的To功能 也可以直接使用DoTween包
标签:Unity3D,轮转,int,CreateCube,float,Mathf,transforms,回正,movehu From: https://blog.csdn.net/djrjnfjdjejb/article/details/139868212