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<ScrollRect>();
        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;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容