Unity UI system 实现NGUI滚动面板UICenterOnChild功能

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;
[RequireComponent(typeof(ScrollRect))]
public class ScrollRectSnap : MonoBehaviour, IDragHandler, IEndDragHandler
{
    [Range(0, 1)]
    public float stepSize;
    private ScrollRect scroll;
    private bool LerpH;
    private float targetH;
    [Tooltip("Snap horizontally")]
    public bool snapInH = true;
    private bool LerpV;
    private float targetV;
    [Tooltip("Snap vertically")]
    public bool snapInV = true;
    public float springStrength = 16f;
    // Use this for initialization
    void Start()
    {
        scroll = gameObject.GetComponent();
        scroll.inertia = false;
    }
    void Update()
    {
        if (LerpH)
        {
            scroll.horizontalNormalizedPosition = Mathf.Lerp(scroll.horizontalNormalizedPosition, targetH, springStrength * scroll.elasticity * Time.deltaTime);
            if (Mathf.Approximately(scroll.horizontalNormalizedPosition, targetH))
                LerpH = false;
        }
        if (LerpV)
        {
            scroll.verticalNormalizedPosition = Mathf.Lerp(scroll.verticalNormalizedPosition, targetV, springStrength * scroll.elasticity * Time.deltaTime);
            if (Mathf.Approximately(scroll.verticalNormalizedPosition, targetV))
                LerpV = false;
        }
    }
    public void OnEndDrag(PointerEventData eventData)
    {
        if (scroll.horizontal && snapInH)
        {
            targetH = FindNearest(scroll.horizontalNormalizedPosition);
            LerpH = true;
        }

        if (scroll.vertical && snapInV)
        {
            targetV = FindNearest(scroll.verticalNormalizedPosition);
            LerpV = true;
        }
    }
    public void OnDrag(PointerEventData eventData)
    {
        LerpH = false;
        LerpV = false;
    }
    float FindNearest(float value)
    {
        value = Mathf.Clamp01(value);
         int index = (int)(value / stepSize);
        if (Mathf.Abs(value - index * stepSize) < Mathf.Abs(value - (index + 1) * stepSize))
            return stepSize * index;
        return (index + 1) * stepSize;
    }
}

你可能感兴趣的:(Unity UI system 实现NGUI滚动面板UICenterOnChild功能)