UNITY 模拟手机滑屏功能

挂到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;
         });
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序丑汉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值