利用Scroll View控件做拖拽自动吸附居中效果
1、新建一个Scrool View控件,去掉两个Scroolbar,因为不需要;
然后在Viewport下建一个CenterPoint空对象跟Content同级作为中心位置用来比较;
最后给Content添加元素。
2、取消垂直拖拽,即去掉Vertical的勾选;Movement Type 设置为Unrestricted,如下图。
3、yiyi对应引用对象;添加Event Trigger组件,再添加Begin Drag和End Drag事件,再调用脚本代码。
4、代码如下
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class testttt : MonoBehaviour {
public RectTransform viewport;
public RectTransform[] elements;
public RectTransform centerPoint;
public RectTransform content;
private Vector2 newPos;
private int distanceBetweenEles;
private float[] distanceToCenter;
private int minEleNum;
private bool isDragging = false;
// Use this for initialization
void Start () {
int elelength = elements.Length;
distanceToCenter = new float[elelength];
//获得元素间隔距离
distanceBetweenEles = (int)Mathf.Abs(elements[1].anchoredPosition.x - elements[0].anchoredPosition.x);
}
void Update()
{
//当前位置跟计算得到吸附位置接近的时候不再进行计算最小位置
if (Vector2.Distance(content.anchoredPosition, newPos)>5f)
{
for (int i = 0; i < elements.Length; i++)
{
//得到每个元素到中心点的距离
distanceToCenter[i] = Mathf.Abs(centerPoint.transform.position.x - elements[i].transform.position.x);
}
//获得最近距离
float minDist = Mathf.Min(distanceToCenter);
for (int i = 0; i < elements.Length; i++)
{
//找到最小距离的元素索引
if (minDist == distanceToCenter[i])
{
minEleNum = i;
}
}
}
if(!isDragging)
{
//当前没有拖拽,自动吸附居中
newPos = new Vector2(minEleNum * -distanceBetweenEles, viewport.anchoredPosition.y);
content.anchoredPosition = Vector2.Lerp(content.anchoredPosition, newPos, Time.deltaTime * 5f);
}
}
public void StartDrag()
{
isDragging = true;
}
public void EndDrag()
{
isDragging = false;
}
}
————————————————
版权声明:本文为CSDN博主「紫阳_368」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/zjh_368/article/details/89315707