您的位置:首页 > 产品设计 > UI/UE

UICenterOnChild

2017-04-18 21:03 337 查看
类似 NGUI 里面的那种效果, 挂在ScrollRect 上就可以了

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System;

[RequireComponent(typeof(ScrollRect))]
public class UICenterOnChild : MonoBehaviour, IBeginDragHandler, IEndDragHandler {

// Use this for initialization
public ScrollRect scrollRect;
public bool isDraging;
public List<float> pageArray = new List<float>();
public int pageIndex;

public float curretPosition;
void Start ()
{
scrollRect = GetComponent<ScrollRect>();
float each = 1f / (scrollRect.content.childCount - 1);
for (int i = 0; i < scrollRect.content.childCount; i++)
{
pageArray.Add(each * i);
}
}

float currentVelocity;
// Update is called once per frame
void Update ()
{
if (!isDraging)
{

scrollRect.horizontalNormalizedPosition = Mathf.Lerp(scrollRect.horizontalNormalizedPosition, pageArray[pageIndex], Time.deltaTime *8);
}

curretPosition = scrollRect.horizontalNormalizedPosition;
}

public void OnBeginDrag(PointerEventData eventData)
{
isDraging = true;
}

public void OnEndDrag(PointerEventData eventData)
{
isDraging = false;

float posX = scrollRect.horizontalNormalizedPosition;
pageIndex = 0;
float offSet = Mathf.Abs(pageArray[pageIndex] - posX);

for (int i = 1; i < pageArray.Count; i++ )
{
float offsetTemp = Mathf.Abs(pageArray[i] - posX);
if (offsetTemp < offSet )
{
pageIndex = i;
offSet = offsetTemp;
}
}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  UICenterOnChild
相关文章推荐