//两个接口 拖拽中和拖拽结束
public class Roate2D : MonoBehaviour,IDragHandler,IEndDragHandler
{
//数量
int n = 5;
//弧度
float rad;
//半径
float r = 500;
//子物体Image
[SerializeField]
Image img;
//轮转结束回正弧度
float moverad;
//两个集合
List<Image> images= new List<Image>();
List<Image> scene=new List<Image>();
// Start is called before the first frame update
void Start()
{
rad = 2 * Mathf.PI / n;
Move();
}
public void Move()
{
for (int i = 0; i < n; i++)
{
if(i>=images.Count)
{
Image item;
if (i == 0)
{
item = img;
}
else
{
item = Instantiate(img);
item.transform.SetParent(transform);
}
//存到两个集合里面
images.Add(item);
scene.Add(item);
images[i].color = Random.ColorHSV();
}
float x = Mathf.Cos(i * rad + Mathf.PI / 2 + moverad) * r;
float y = Mathf.Sin(i * rad + Mathf.PI / 2 + moverad) * r;
images[i].transform.localPosition=new Vector3(x, 0, 0);
float c = Mathf.Lerp(0.5f, 1, (y + r) / (r * 2));
images[i].transform.localScale=new Vector3 (c, c, c);
}
//排序缩放
scene.Sort((a, b) =>
{
return (int) ((a.transform.localScale.x - b.transform.localScale.x)*100);
});
for (int i = 0; i < scene.Count; i++)
{
scene[i].transform.SetSiblingIndex(i);
}
}
//拖拽中
public void OnDrag(PointerEventData eventData)
{
moverad-=eventData.delta.x*Time.deltaTime;
Move();
}
//拖拽结束
public void OnEndDrag(PointerEventData eventData)
{
float needmoverad;
float offsef = Mathf.Abs(moverad) % rad;
if(offsef < rad / 2)
{
needmoverad= -offsef;
}
else
{
needmoverad = rad - offsef;
}
if(moverad < 0)
{
needmoverad = -needmoverad;
}
//利用DOTween
DOTween.To((a) =>
{
moverad = a;
Move();
},moverad, moverad+ needmoverad,1);
}
}
需要DOTween插件 没有的可以去官网下载
下面是自己写的一个DoTween 效果和插件是一样的 直接建一个脚本就可以 赋值进去
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class Dotween : MonoBehaviour
{
public Action<float> action;
public float begin;
public float end;
public float timer;
public float beginTime;
Action onComplete;
public static Dotween To(Action<float> action, float begin, float end, float t)
{
GameObject go = new GameObject("DT");
Dotween dt = go.AddComponent<Dotween>();
dt.action = action;
dt.begin = begin;
dt.end = end;
dt.timer = t;
dt.beginTime = Time.time;
return dt;
}
public void OnComplete(Action complete)
{
this.onComplete = complete;
}
private void Update()
{
if (Time.time - beginTime < timer)
{
float ration = (Time.time - beginTime) / timer;
float offSet = ration * (end - begin) + begin;
//float offSet = Mathf.Lerp(end, begin, (Time.time - beginTime) / timer);
action(offSet);
}
else
{
action(end);
if (onComplete != null)
{
onComplete();
}
Destroy(gameObject);
}
}
}