unity_UGUI养成之路03
Posted 爱上游戏开发
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了unity_UGUI养成之路03相关的知识,希望对你有一定的参考价值。
关卡分页设计
功能1:通过直接滑动:
添加自动排序组件
设置通过添加组件设置内容的滑动,多余内容的隐藏
功能2:通过点击下面的圆圈滑动
上述代码实现:
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class LevelButtonScrollRect : MonoBehaviour ,IBeginDragHandler,IEndDragHandler
{
private ScrollRect scrollRect;
public float smoothing = 4; //插值的速度
private float[] pageArray=new float[]{ 0,0.33333f,0.66666f,1 }; //每个页面X轴坐标
private float targetHorizontalPosition=0; //距离最近页面的X坐标
private bool isDraging = false; //是否拖拽的标志位
public Toggle[] toggleArray; //圆圈数组
void Start ()
{
scrollRect = GetComponent<ScrollRect>();
}
void Update ()
{
if(isDraging==false)
scrollRect.horizontalNormalizedPosition = Mathf.Lerp(scrollRect.horizontalNormalizedPosition,
targetHorizontalPosition, Time.deltaTime*smoothing);
}
public void OnBeginDrag(PointerEventData eventData)
{
isDraging = true;
}
public void OnEndDrag(PointerEventData eventData)
{
isDraging = false;
//找到当前位置与每页距离最小的页面,并切换到该页面
float posX = scrollRect.horizontalNormalizedPosition;
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;
}
}
targetHorizontalPosition = pageArray[index];
toggleArray[index].isOn = true;
//scrollRect.horizontalNormalizedPosition = pageArray[index];
}
public void MoveToPage1(bool isOn) {
if (isOn)
{
targetHorizontalPosition = pageArray[0];
}
}
public void MoveToPage2(bool isOn) {
if (isOn) {
targetHorizontalPosition = pageArray[1];
}
}
public void MoveToPage3(bool isOn) {
if (isOn)
{
targetHorizontalPosition = pageArray[2];
}
}
public void MoveToPage4(bool isOn) {
if (isOn)
{
targetHorizontalPosition = pageArray[3];
}
}
}
以上是关于unity_UGUI养成之路03的主要内容,如果未能解决你的问题,请参考以下文章