最近要实现一个左右滑动图片和文字居中显示的功能,其实也可以理解为Scroll添加了Layout组件让第一个就居中,然后让每个UI保持相同的间距,每一次在屏幕上的手指滑动,UI都是滑动了相同的距离。用下面的脚本替换原来的ScrollRect即可:
using DG.Tweening;
using DG.Tweening.Core;
using DG.Tweening.Plugins.Options;
using System;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class SameDistanceScroll : ScrollRect
{
public Action<int> endDragAction;
private int _totalIndex = 10;
private int _nowIndex = 0;
private bool _isIndexChanged;
private float _beginX, _endX, _beginNormalPos;
private static TweenerCore<float, float, FloatOptions> tween;
public void Init(int totalIndex, int nowIndex = 0)
{
_totalIndex = totalIndex;
_nowIndex = nowIndex;
DOTween.To(() => horizontalNormalizedPosition, (x) => horizontalNormalizedPosition = x, (float)_nowIndex / (_totalIndex - 1), 0);
}
public override void OnBeginDrag(PointerEventData eventData)
{
tween.Complete();
base.OnBeginDrag(eventData);
_beginX = eventData.position.x;
_beginNormalPos = horizontalNormalizedPosition;
}
public override void OnEndDrag(PointerEventData eventData)
{
base.OnEndDrag(eventData);
_isIndexChanged = false;
_endX = eventData.position.x;
var distance = _beginX - _endX;
if ( Mathf.Abs(distance) > 100f)
{
if (horizontalNormalizedPosition - _beginNormalPos < 0f)
{
if (_nowIndex > 0)
{
_nowIndex--;
_isIndexChanged = true;
}
}
else
{
if (_nowIndex < _totalIndex - 1)
{
_nowIndex++;
_isIndexChanged = true;
}
}
}
_beginX = 0;
_endX = 0;
if (horizontal)
{
tween = DOTween.To(() => horizontalNormalizedPosition, (x) => horizontalNormalizedPosition = x, (float)_nowIndex / (_totalIndex - 1), 0.5f);
tween.onComplete += () => {
if (_isIndexChanged)
endDragAction?.Invoke(_nowIndex);};
}
}
}