1. 程式人生 > >unity_UGUI養成之路03

unity_UGUI養成之路03

sin -1 ugui oid handle .com events alt lec

關卡分頁設計

功能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