本次主要实现了滑动关卡页面的制作以及通过Toggle来实现页面的跳转。具体实现如下:
ScrollPanel上挂载脚本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
/*
* 实现页面的切换
*实现页面的滑动效果
*/
public class LevelButtonScrollRect : MonoBehaviour, IBeginDragHandler,IEndDragHandler //引用两个接口
{
private ScrollRect scrollRect;
private float[] pageArray = new float[] { 0, 190, 380, 560 };
private float targetHorizoontalPosition=0;
private bool isDraging = false;
public Toggle[] toggles;
// Start is called before the first frame update
void Start()
{
//获得滑动组件
scrollRect = transform.GetComponent<ScrollRect>();
}
// Update is called once per frame
void Update()
{
if(isDraging==false)
//实现页面的滑动效果,滑动速度可以改变
scrollRect.horizontalNormalizedPosition = Mathf.Lerp(scrollRect.horizontalNormalizedPosition, targetHorizoontalPosition, Time.deltaTime*4);
}
public void OnBeginDrag(PointerEventData eventData)
{
isDraging = true;
}
public void OnEndDrag(PointerEventData eventData)
{
isDraging = false;
//获得滑动组件结束滑动的水平位置
float posX = scrollRect.horizontalNormalizedPosition;
print(posX);
int index = 0;
//第一页位置和结束滑动距离的绝对值
float offset = Mathf.Abs(pageArray[index] - posX);
for (int i = 1; i < pageArray.Length; i++)
{
float offsetTemp = Mathf.Abs(pageArray[i] - posX);
if (offsetTemp < offset)
{
index = i;
offset = offsetTemp;
}
}
//表示第几页的滑窗位置
targetHorizoontalPosition= pageArray[index];
toggles[index].isOn = true;
//scrollRect.horizontalNormalizedPosition = pageArray[index];
}
#region 以下主要实现了通过Toggle开关,进行页面滑动的功能
public void GuanKaSelected0(bool isOn)
{
if (isOn)
targetHorizoontalPosition = 0;
}
public void GuanKaSelected1(bool isOn)
{
if (isOn)
targetHorizoontalPosition = 190;
}
public void GuanKaSelected2(bool isOn)
{
if (isOn)
targetHorizoontalPosition = 380;
}
public void GuanKaSelected3(bool isOn)
{
if (isOn)
targetHorizoontalPosition = 560;
}
#endregion
}
补充Toggle如下图:
最终实现效果见下图:
效果视频:
Unity滑动页面效果