一、效果
二、上代码,两种方式。
(第一种是在Update中用插值完成的,如果不想再项目中看到Update,下面的另一种改了一段用DoTween实现的,需要导入一下DoTween)
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public enum ScrollDir
{
Horizontal,
Vertical
}
public class CenterOnChild : MonoBehaviour, IEndDragHandler, IDragHandler, IBeginDragHandler
{
public ScrollDir Dir = ScrollDir.Horizontal;
/// <summary>
/// 是否正在居中
/// </summary>
private bool _isCentering = false;
[Header("居中过程移动速度")]
public float MoveToCenterSpeed = 10f;
[Header("中心点放大倍数")]
public float CenterScale = 1f;
[Header("非中心点放大倍数")]
public float UnCenterScale = 0.9f;
private ScrollRect _scrollView;
private Transform _content;
private List<float> _childrenPos = new List<float>();
private float _targetPos;
/// <summary>
/// 当前中心child索引
/// </summary>
private int _curCenterChildIndex = -1;
/// <summary>
/// 当前中心ChildItem
/// </summary>
public GameObject CurCenterChildItem
{
get
{
GameObject centerChild = null;
if (_content != null && _curCenterChildIndex >= 0 && _curCenterChildIndex < _content.childCount)
{
centerChild = _content.GetChild(_curCenterChildIndex).gameObject;
}
return centerChild;
}
}
/// <summary>
/// 根据拖动来改变每一个子物体的缩放
/// </summary>
public void SetCellScale()
{
GameObject centerChild = null;
for (int i = 0; i < _content.childCount; i++)
{
centerChild = _content.GetChild(i).gameObject;
if (i == _curCenterChildIndex)
centerChild.transform.localScale = CenterScale * Vector3.one;
else
centerChild.transform.localScale = UnCenterScale * Vector3.one;
}
}
void Awake()
{
_scrollView = GetComponent<ScrollRect>();
if (_scrollView == null)
{
Debug.LogError("ScrollRect is null");
return;
}
_content = _scrollView.content;
LayoutGroup layoutGroup = null;
layoutGroup = _content.GetComponent<LayoutGroup>();
if (layoutGroup == null)
{
Debug.LogError("LayoutGroup component is null");
}
_scrollView.movementType = ScrollRect.MovementType.Unrestricted;
float spacing = 0f;
//根据dir计算坐标,Horizontal:存x,Vertical:存y
switch (Dir)
{
case ScrollDir.Horizontal:
if (layoutGroup is HorizontalLayoutGroup)
{
float childPosX = _scrollView.GetComponent<RectTr