挂到ScrollRect组上,模拟手机滑屏功能
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using DG.Tweening;
using DG.Tweening.Core;
using DG.Tweening.Plugins.Options;
/// <summary>
/// 鼠标滑动 模仿手机桌面
/// </summary>
public class UIDragScroll : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
ScrollRect scrollRect;
Scrollbar scrollbar;
//拖动动画
TweenerCore<float, float, FloatOptions> tweenerCore;
//每页的大小
float itemSize;
//内容页
Transform content;
//孩子个数
int childCount;
//每个step的value
float[] stepValueArr;
private void Start()
{
scrollRect = GetComponent<ScrollRect>();
scrollbar = scrollRect.horizontalScrollbar;
itemSize = scrollRect.viewport.rect.width;
content = scrollRect.content;
childCount = content.transform.childCount;
stepValueArr = new float[childCount];
for (int i = 0; i < stepValueArr.Length - 1; i++)
{
stepValueArr[i] = i * (1f / (childCount - 1));
}
stepValueArr[stepValueArr.Length - 1] = 1;
}
public void OnPointerDown(PointerEventData eventData)
{
if (tweenerCore != null)
{
tweenerCore.Kill();
tweenerCore = null;
}
}
public void OnPointerUp(PointerEventData eventData)
{
float currValue = scrollbar.value;
float middleValue;
float targetValue = 1;
if (currValue >= 1)
{
targetValue = 1;
}
else
{
for (int i = 0; i < stepValueArr.Length - 1; i++)
{
middleValue = (stepValueArr[i] + stepValueArr[i + 1]) / 2;
if (currValue <= middleValue)
{
targetValue = stepValueArr[i];
break;
}
}
}
float val = scrollbar.value;
tweenerCore = DOTween.To(() => val, x => val = x, targetValue, 0.5f).OnUpdate(() =>
{
scrollbar.value = val;
});
}
}