Unity实现一次一页的滑动效果(可以直接使用)

效果展示

在这里插入图片描述
有鼠标拖动来直接实现滑动

实现步骤

第一步创建Scroll View UI

在这里插入图片描述
在场景里面创建Scroll View UI

第二步挂载Grid Layout Group组件

在这里插入图片描述
找到下面的Content物体
给其挂载Grid Layout Group组件,并且按照自己需求设置里面的内容
在这里插入图片描述

第三步添加脚本

给Scroll View组件添加我们自己写的脚本SlideScrollView
脚本如下

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

public class SlideScrollView : MonoBehaviour,IBeginDragHandler,IEndDragHandler
{
    private RectTransform contentTrans;
    private float beginMousePositionX;
    private float endMousePositionX;
    private ScrollRect scrollRect;

    public int cellLength;
    public int spaceing;
    public int leftOffset;

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

    public int totalItemNum;
    private int currenIndex;
    private void Awake()
    {
        scrollRect = GetComponent<ScrollRect>();
        contentTrans = scrollRect.content;
        moveOneItemLength = cellLength + spaceing;
        currentContentLocalPos = contentTrans.localPosition;
        currenIndex = 1;
    }

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


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

        DOTween.To(() => contentTrans.localPosition, lerpValue => contentTrans.localPosition = lerpValue, currentContentLocalPos + new Vector3(moveDistance, 0, 0), 0.5f).SetEase(Ease.InOutQuint);
        currentContentLocalPos += new Vector3(moveDistance, 0, 0);
    }

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

第四步赋值

在Unity给脚本里赋值
在这里插入图片描述
说明:
Cell Length:为Grid Layout Group组件的Cell Size的x的值
Spaceing:为Grid Layout Group组件的Spacing的x的值
LeftOffset:为Grid Layout Group组件的Padding的Left的值
TotalItemNum:为总共要滑动的物体的个数

在这里插入图片描述

重要说明

代码中使用了DoTween插件
需要去官网下载插件:DoTween
下载后将其解压直接拖入项目中就可以使用了
可以将Scroll View中的惯性√去掉来获得更好的效果

  • 5
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值