1,准备工作:先把周长,半径,弧度,计算出
2,对每一个image的Mathf.Sin和Mathf.Cos进行赋值,对其anchoredPosition赋值,用最大值最小值计算出倍率,算出缩放倍率,然后对transform集合进行排序
3,计算出位移和时间, 利用DoTween.To进行转动
代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class CreateImage4 : MonoBehaviour,IDragHandler,IEndDragHandler
{
public int n = 14;
public float c;
public float r;
float ang;
public Image prefab;
public float spacing;
List<Image> list = new List<Image>();
List<Transform> tlist = new List<Transform>();
float moving;
float max = 1;
float min = 0.5f;
float slow = 100;
// Start is called before the first frame update
void Start()
{
c = (prefab.rectTransform.rect.width + spacing) * n;
r = c / (2 * Mathf.PI);
ang = 2 * Mathf.PI / n;
Move();
}
public void Sort()
{
tlist.Sort((a, b) =>
{
if (a.localScale.x < b.localScale.x)
{
return -1;
}
else if (a.localScale.x == b.localScale.x)
{
return 0;
}
else
{
return 1;
}
});
}
public void Move()
{
for (int i = 0; i < n; i++)
{
if(list.Count<=i)
{
list.Add(Instantiate(prefab, transform));
tlist.Add(list[i].transform);
}
float x = Mathf.Sin(i * ang + moving) * r;
float z = Mathf.Cos(i * ang + moving) * r;
float p = (z + r) / (2 * r);
float scale = (max - min) * p + min;
list[i].rectTransform.anchoredPosition = new Vector2(x, 0);
list[i].transform.localScale = Vector3.one * scale;
}
Sort();
for (int i = 0; i < list.Count; i++)
{
list[i].transform.SetSiblingIndex(i);
}
}
public void OnDrag(PointerEventData eventData)
{
float des = eventData.delta.x;
float desang = des / r;
moving += desang;
Move();
}
public void OnEndDrag(PointerEventData eventData)
{
float des = eventData.delta.x;
float time =Mathf.Abs(des) / slow;
DOTween.To((a) =>
{
float aang = a / r;
moving += aang;
Move();
}, des, 0, time).OnComplete(() =>
{
Align(list.IndexOf(tlist[n - 1].GetComponent<Image>()));
});
}
public void Align(int id)
{
int index = list.IndexOf(tlist[n - 1].GetComponent<Image>());
int sp = id - index;
float spang = sp * ang;
float alignang = Mathf.Asin(tlist[n-1].GetComponent<RectTransform>().anchoredPosition.x / r + spang);
float aligndes = alignang * r;
float time = Mathf.Abs(aligndes) / slow;
DOTween.To((a) =>
{
moving = a;
Move();
}, moving, moving - alignang, time);
}
}