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键后选择最右下角的那一个!)

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Defining the Future

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

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

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

打赏作者

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

抵扣说明:

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

余额充值