Unity中改变horizontalNormalizedPosition值从⽽实现页⾯切换效果
⾸先在Unity中新建⼀个脚本SlideCanCoverScrollView,把这个脚本绑定在拥有ScrollView组件的游戏物体上⾯。然后复制以下的代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System;
using DG.Tweening;
public class SlideCanCoverScrollView : MonoBehaviour,IBeginDragHandler,IEndDragHandler
{
private float contentLength;//容器长度
private float beginMouPositionX;//⿏标开始拖拽的X值
private float endMouPositionX;//⿏标结束拖拽的X值
private ScrollRect scrollRect;//绑定这个脚本上⾃⾝游戏物体上的的ScrollRect组件
private float lastProportion;//上⼀个位置的⽐例
public int cellLength;//每个单元格的长度(这⾥的长度指的是Content下的单个⼦元素的长度)
public int spacing;//间隔(指的是两个⼦元素之间的间距)
public int leftOfft;//左偏移量(指的是页⾯最左边距离屏幕最左边的距离)
private float upperLimit;//上限值
private float lowerLimit;//下限值
private float firstItemLength;//移动第⼀个单元格的距离
private float oneItemLength;//滑动⼀个单元格需要的距离
private float oneItemProportion;//滑动⼀个单元格所占的⽐例
public int totalItemNum;//共有⼏个单元格(在这⾥单元格其实指的就是Content下的元素个数)
private int currentIndex;//当前单元格的索引
private void Awake()
{
scrollRect =GetComponent<ScrollRect>();
contentLength = Max;
firstItemLength = cellLength /2+ leftOfft;
oneItemLength = cellLength + spacing;
oneItemProportion = oneItemLength / contentLength;
upperLimit =1- firstItemLength / contentLength;
lowerLimit = firstItemLength / contentLength;
currentIndex =1;
scrollRect.horizontalNormalizedPosition =0;
}
public void OnBeginDrag(PointerEventData eventData)
{
beginMouPositionX = uPosition.x;
}
public void OnEndDrag(PointerEventData eventData)
{
float offSetX =0;
endMouPositionX = uPosition.x;
offSetX =(beginMouPositionX - endMouPositionX)*2;
//Debug.Log("offSetX:" + offSetX);
//Debug.Log("firstItemLength:" + firstItemLength);
if(Mathf.Abs(offSetX)> firstItemLength)//执⾏滑动动作的前提是要⼤于第⼀个需要滑动的距离
{
if(offSetX >0)//右滑
{
if(currentIndex >= totalItemNum)
{
return;
}
}
int moveCount =
(int)((offSetX - firstItemLength)/ oneItemLength)+1;//当次可以移动的格⼦数⽬
currentIndex += moveCount;
if(currentIndex >= totalItemNum)
{
currentIndex = totalItemNum;
}
//当次需要移动的⽐例:上⼀次已经存在的单元格位置
/
/的⽐例加上这⼀次需要去移动的⽐例
lastProportion += oneItemProportion * moveCount;
if(lastProportion >= upperLimit)
{
lastProportion =1;
}
}
el//左滑
{
if(currentIndex <=1)
{
return;
}
int moveCount =
(int)((offSetX + firstItemLength)/ oneItemLength)-1;//当次可以移动的格⼦数⽬
currentIndex += moveCount;
if(currentIndex <=1)
{
currentIndex =1;
}
//当次需要移动的⽐例:上⼀次已经存在的单元格位置
//的⽐例加上这⼀次需要去移动的⽐例
lastProportion += oneItemProportion * moveCount;
if(lastProportion <= lowerLimit)
{
lastProportion =0;
}
}
}
DOTween.To(()=> scrollRect.horizontalNormalizedPosition,
lerpValue => scrollRect.horizontalNormalizedPosition = lerpValue,
lastProportion,0.5f).SetEa(Ea.OutQuint);
}
}
保存,然后回到Unity中等到代码编译完成后,就可以对我们在代码中公开的变量根据我注释的意思进⾏赋值。(在这⾥⼀定要注意的是要把Scroll View这个组件下的Content的Anchor Prets(锚点定位),在按下Alt键后选择最右下⾓的那⼀个!)