通过按钮或者滑动翻页
//太懒了不想截图…
using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;
using UnityEngine.EventSystems;
public class FlipOver : MonoBehaviour,IBeginDragHandler,IEndDragHandler
{
//获取组件
ScrollRect rect;
//每张图片的位置
private float[] posArray = new float[] { 0f, 0.25f, 0.5f, 0.75f, 1.0f };
//滚动的目标点
private float targetPos;
//是否正在拖拽
private bool isDrag = false;
//记录下标
int index = 0;
[Header("左翻页按钮")]
public Button leftBtn;
[Header("右翻页按钮")]
public Button rightBtn;
public void OnBeginDrag(PointerEventData eventData)
{
//开始拖动
isDrag = true;
}
public void OnEndDrag(PointerEventData eventData)
{
//停止拖动
isDrag = false;
//获取当前的位置
Vector2 pos = rect.normalizedPosition;
//记录位置
float x = Mathf.Abs(pos.x - posArray[0]);
for (int i = 0; i < 5; i++)
{
//记录当前图片的位置
float temp = Mathf.Abs(pos.x - posArray[i]);
if (temp <= x)
{
x = temp;
//记录索引
index = i;
}
}
//移动到目标位置
targetPos = posArray[index];
}
private void Start()
{
//获取组件
rect = GetComponent<ScrollRect>();
//给按钮添加监听事件
leftBtn.onClick.AddListener(LeftBtn);
rightBtn.onClick.AddListener(RightBtn);
}
void Update()
{
//只有在非拖拽的情况下才可以移动
if (!isDrag)
{
//进行移动
rect.horizontalNormalizedPosition = Mathf.Lerp(rect.horizontalNormalizedPosition, targetPos, Time.deltaTime * 4);
}
}
//点击左按钮
public void LeftBtn()
{
//获取当前的位置
Vector2 pos = rect.normalizedPosition;
//其实就是目标位置
pos.x -= 0.25f;
//记录位置
float x = Mathf.Abs(pos.x - posArray[0]);
for (int i = 0; i < 5; i++)
{
//记录当前图片的位置
float temp = Mathf.Abs(pos.x - posArray[i]);
if (temp <= x)
{
x = temp;
//记录索引
index = i;
}
}
//移动到目标位置
targetPos = posArray[index];
}
//点击右按钮
public void RightBtn()
{
//获取当前的位置
Vector2 pos = rect.normalizedPosition;
//其实是目标位置
pos.x += 0.25f;
//记录位置
float x = Mathf.Abs(pos.x - posArray[0]);
for (int i = 0; i < 5; i++)
{
//记录当前图片的位置
float temp = Mathf.Abs(pos.x - posArray[i]);
if (temp <= x)
{
x = temp;
//记录索引
index = i;
}
}
//移动到目标位置
targetPos = posArray[index];
}
}