118 lines
3.1 KiB
C#
118 lines
3.1 KiB
C#
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);
|
||
}
|
||
} |