PageView脚本

This commit is contained in:
yangjing 2022-02-12 20:01:05 +08:00
parent 276eed0f3c
commit 6b34fe2185
2 changed files with 129 additions and 0 deletions

View File

@ -0,0 +1,118 @@
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Collections.Generic;
using UnityEngine.EventSystems;
using System;
public class PageView : MonoBehaviour, IBeginDragHandler, IEndDragHandler
{
public int PageCount;
public float SlideSpeed = 4; //滑动速度
public float sensitivity = 0.3f;
public Action<int> OnPageChanged;
ScrollRect rect; //滑动组件
private float targethorizontal = 0; //滑动的起始坐标
private bool isDrag = false; //是否拖拽结束
List<float> posList = new List<float>();//求出每页的临界角页索引从0开始
private int currentPageIndex = -1;
private bool stopMove = true;
private float startTime;
private float startDragHorizontal;
void Awake()
{
rect = transform.GetComponent<ScrollRect>();
int tSplitCount = Mathf.Max(1, PageCount);
float tDelta = tSplitCount > 1 ? (1f / (tSplitCount - 1)) : 1;
for (int i = 0; i < tSplitCount; i++)
{
posList.Add(tDelta * i);
}
}
void Update()
{
if (!isDrag && !stopMove)
{
startTime += Time.deltaTime;
float t = startTime * SlideSpeed;
rect.horizontalNormalizedPosition = Mathf.Lerp(rect.horizontalNormalizedPosition, targethorizontal, t);
if (t >= 1)
stopMove = true;
}
}
public void PageFix(int index)
{
PageTo(index, false);
}
public void PageScroll(int index)
{
PageTo(index);
}
public void PageTo(int index, bool pWithScroll = true)
{
if (index >= 0 && index < posList.Count)
{
if (currentPageIndex != index)
{
currentPageIndex = index;
if (OnPageChanged != null)
OnPageChanged(index);
}
if (pWithScroll)
{
targethorizontal = posList[currentPageIndex]; //设置当前坐标,更新函数进行插值
isDrag = false;
startTime = 0;
stopMove = false;
}
else
{
rect.horizontalNormalizedPosition = posList[index];
}
}
else
{
Debug.LogError("页码不存在");
}
}
public void OnBeginDrag(PointerEventData eventData)
{
isDrag = true;
startDragHorizontal = rect.horizontalNormalizedPosition;
}
public void OnEndDrag(PointerEventData eventData)
{
float posX = rect.horizontalNormalizedPosition;
posX += ((posX - startDragHorizontal) * sensitivity);
posX = posX < 1 ? posX : 1;
posX = posX > 0 ? posX : 0;
int index = 0;
float offset = Mathf.Abs(posList[index] - posX);
for (int i = 1; i < posList.Count; i++)
{
float temp = Mathf.Abs(posList[i] - posX);
if (temp < offset)
{
index = i;
offset = temp;
}
}
PageTo(index);
}
}

View File

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: b740f51fd170d492fbc0b5189d6de998
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: