在游戏的界面菜单需要每次滑动后都定位到中间位置,是界面可以展示3个菜单。一想很简单,实现OnEndDrag方法后用Hotween来定位到之前的位置。
public void OnEndDrag(GameObject go)
{
float ToPoint = GetClosestPoint(scrollContent.localPosition.x, new float[] { -540,-896,-1254 });
Debuger.Log(ToPoint);
TweenParms parms = new TweenParms();
parms.Prop("localPosition", new Vector3(ToPoint,scrollContent.localPosition.y, 0));
parms.Ease(EaseType.Linear);
HOTween.To(scrollContent, 0.2f, parms);
}
public float GetClosestPoint(float point, float[] comparePoints) //获取最近的定位点
{
float closepoint=comparePoints[0];
float closevalue = Mathf.Abs(Mathf.Abs(comparePoints[0]) - Mathf.Abs(point));
for(int i=1;i<comparePoints.Length;i++)
{
if (Mathf.Abs(Mathf.Abs(comparePoints[i]) - Mathf.Abs(point)) < closevalue)
{
closevalue=Mathf.Abs(Mathf.Abs(comparePoints[i]) - Mathf.Abs(point));
closepoint = comparePoints[i];
}
}
return closepoint;
}
这是最后的实现代码,开始一直纠结移动动画的位置老是不对,锚点一直不能到指定位置。后来才发现用了localPosition 后定位锚点也必须是localPosition坐标。我之前一直在对RectTransform.anchoredPosition的x轴操作,发现动画怎么都不能达到对应的位置,因为滑动的物体最直观的X轴值变化就是它,但是并没有用。自己对Hotween的理解还是不够深刻,所以记下来以后遇到看一下。