Unity中改变RectTransform的localPosition值从而实现页面切换效果

首先在Unity中新建一个脚本SliderScrollView,把这个脚本绑定在拥有ScrollView组件的游戏物体上面。然后复制以下的代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System;
using DG.Tweening;

/// <summary>
/// 多滑处理(每次滑动的时候会有两个出现)
/// </summary>
public class SliderScrollView : MonoBehaviour,IBeginDragHandler,IEndDragHandler
{
    
    
    private RectTransform contentTrans;
    private float beginMousePositionX;
    private float endMousePositionX;
    private ScrollRect scrollRect;

    public int cellLength;
    public int spacing;
    public int leftOffset;
    private float moveOneItemLength;

    private Vector3 currentContentLocalPos;  //上一次的位置

    public int totalItemNum;
    private int currentIndex;

    void Awake()
    {
    
    
        scrollRect = GetComponent<ScrollRect>();
        contentTrans = scrollRect.content;
        moveOneItemLength = cellLength + spacing;
        currentContentLocalPos = contentTrans.localPosition;
        currentIndex = 1;
    }

    public void OnBeginDrag(PointerEventData eventData)
    {
    
    
        beginMousePositionX = Input.mousePosition.x;
    }

    public void OnEndDrag(PointerEventData eventData)
    {
    
    
        endMousePositionX = Input.mousePosition.x;
        float offSetX = 0;
        float moveDistance = 0;//当次需要滑动的距离
        offSetX = beginMousePositionX - endMousePositionX;

        if (offSetX > 0)    //右滑
        {
    
    
            if (currentIndex >= totalItemNum)
            {
    
    
                return;
            }
            moveDistance = -moveOneItemLength;
            currentIndex++;
        }
        else //左滑
        {
    
    
            if (currentIndex <= 1)
            {
    
    
                return;
            }
            moveDistance = moveOneItemLength;
            currentIndex--;
        }

        DOTween.To(() => contentTrans.localPosition,
    lerpValue => contentTrans.localPosition = lerpValue,
    currentContentLocalPos, 0.5f).SetEase(Ease.OutQuint);

        currentContentLocalPos += new Vector3(moveDistance, 0, 0);
    }
}

保存,然后回到Unity中等到代码编译完成后,就可以对我们在代码中公开的变量根据我注释的意思进行赋值。(在这里一定要注意的是要把Scroll View这个组件下的Content的Anchor Presets(锚点定位),在按下Alt键后选择最右下角的那一个!)

猜你喜欢

转载自blog.csdn.net/jianjianshini/article/details/112387882