Unity UGUI 分页滑动

using UnityEngine;

using System.Collections;

using UnityEngine.EventSystems;

using System;

using UnityEngine.UI;

public class LevelButtonScrollRect : MonoBehaviour, IBeginDragHandler, IEndDragHandler

{

private ScrollRect scrollRect;

private float[] pageArray = new float[] { 0, 0.333f, 0.666f, 1 };

public Toggle[] ToggleArray;

private float speed = 5f;

private float targetHorizontalPosition = 0f;

private bool isDraging = false;

void Start()

{

scrollRect = transform.GetComponent();

}

 

void Update()

{

if (!isDraging)

{

scrollRect.horizontalNormalizedPosition = Mathf.Lerp(scrollRect.horizontalNormalizedPosition,

targetHorizontalPosition, Time.deltaTime * speed);

}

}

public void OnBeginDrag(PointerEventData eventData)

{

isDraging = true;

}

public void OnEndDrag(PointerEventData eventData)

{

isDraging = false;

// 得到 水平滑动的 值 (0-1)

float posX = scrollRect.horizontalNormalizedPosition;

int index = 0;

float offset = Mathf.Abs(posX - pageArray[index]);

// 与 前后比较 距离最短

for (int i = 1; i < pageArray.Length; i++)

{

// 距离 最短

float offsetTemp = Mathf.Abs(posX - pageArray[i]);

if (offset > offsetTemp)

{

index = i;

offset = offsetTemp;

}

}

targetHorizontalPosition = pageArray[index];

ToggleArray[index].isOn = true;

}

}

你可能感兴趣的:(c#)