UGUI ScrollRect實現(xiàn)帶按鈕翻頁支持拖拽
更新時間:2020年05月22日 09:06:50 作者:代碼妖
這篇文章主要為大家詳細(xì)介紹了UGUI ScrollRect實現(xiàn)帶按鈕翻頁支持拖拽,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了UGUI ScrollRect帶按鈕翻頁支持拖拽的具體代碼,供大家參考,具體內(nèi)容如下
using UnityEngine; using System.Collections; using UnityEngine.UI; using UnityEngine.EventSystems; using System.Collections.Generic; using System; /// <summary> /// 略知CSharp /// </summary> public class ScrollRectHelper : MonoBehaviour, IBeginDragHandler, IEndDragHandler { public float smooting = 5; //滑動速度 public List<GameObject> listItem; //scrollview item public int pageCount = 3; //每頁顯示的項目 ScrollRect srect; float pageIndex; //總頁數(shù) bool isDrag = false; //是否拖拽結(jié)束 List<float> listPageValue = new List<float> { 0 }; //總頁數(shù)索引比列 0-1 float targetPos = 0; //滑動的目標(biāo)位置 float nowindex = 0; //當(dāng)前位置索引 void Awake() { srect = GetComponent<ScrollRect>(); ListPageValueInit(); } //每頁比例 void ListPageValueInit() { pageIndex = (listItem.Count / pageCount)-1; if (listItem != null && listItem.Count != 0) { for (float i = 1; i <= pageIndex; i++) { listPageValue.Add((i / pageIndex)); } } } void Update() { if (!isDrag) srect.horizontalNormalizedPosition = Mathf.Lerp(srect.horizontalNormalizedPosition, targetPos, Time.deltaTime * smooting); } /// <summary> /// 拖動開始 /// </summary> /// <param name="eventData"></param> public void OnBeginDrag(PointerEventData eventData) { isDrag = true; } /// <summary> /// 拖拽結(jié)束 /// </summary> /// <param name="eventData"></param> public void OnEndDrag(PointerEventData eventData) { isDrag = false; var tempPos = srect.horizontalNormalizedPosition; //獲取拖動的值 var index = 0; float offset = Mathf.Abs(listPageValue[index] - tempPos); //拖動的絕對值 for (int i = 1; i < listPageValue.Count; i++) { float temp = Mathf.Abs(tempPos - listPageValue[i]); if (temp < offset) { index = i; offset = temp; } } targetPos = listPageValue[index]; nowindex = index; } public void BtnLeftGo() { nowindex = Mathf.Clamp(nowindex - 1, 0, pageIndex); targetPos = listPageValue[Convert.ToInt32(nowindex)]; } public void BtnRightGo() { nowindex = Mathf.Clamp(nowindex + 1, 0, pageIndex); targetPos = listPageValue[Convert.ToInt32(nowindex)]; } }
DEMO 下載地址
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
c# winform窗口一直置頂顯示在桌面最上方或最底層的方法
winform窗口一直置頂顯示在桌面最上方,這樣的功能真的很實用的,很多的軟件窗口都有這樣的功能,本文也來實現(xiàn)一個,感興趣的你千萬不要錯過了,希望本文對你有所幫助2013-01-01C#使用throw和throw?ex拋出異常的區(qū)別介紹
這篇文章介紹了C#使用throw和throw?ex拋出異常的區(qū)別,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-10-10C#簡單獲取全屏中鼠標(biāo)焦點位置坐標(biāo)的方法示例
這篇文章主要介紹了C#簡單獲取全屏中鼠標(biāo)焦點位置坐標(biāo)的方法,涉及C#針對鼠標(biāo)位置Position屬性的簡單操作技巧,需要的朋友可以參考下2017-07-07