Guest User

HorizontalScrollSnap

a guest
May 8th, 2018
183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 10.24 KB | None | 0 0
  1. /// Credit BinaryX
  2. /// Sourced from - http://forum.unity3d.com/threads/scripts-useful-4-6-scripts-collection.264161/page-2#post-1945602
  3. /// Updated by ddreaper - removed dependency on a custom ScrollRect script. Now implements drag interfaces and standard Scroll Rect.
  4.  
  5. using UnityEngine.EventSystems;
  6.  
  7. namespace UnityEngine.UI.Extensions
  8. {
  9.  
  10.     [RequireComponent(typeof(ScrollRect))]
  11.     [AddComponentMenu("Layout/Extensions/Horizontal Scroll Snap")]
  12.     public class HorizontalScrollSnap : ScrollSnapBase, IEndDragHandler
  13.     {
  14.         void Start()
  15.         {
  16.             _isVertical = false;
  17.             _childAnchorPoint = new Vector2(0, 0.5f);
  18.             _currentPage = StartingScreen;
  19.             panelDimensions = gameObject.GetComponent<RectTransform>().rect;
  20.             UpdateLayout();
  21.         }
  22.  
  23.         void Update()
  24.         {
  25.             if (!_lerp && _scroll_rect.velocity == Vector2.zero)
  26.             {
  27.                 if (!_settled && !_pointerDown)
  28.                 {
  29.                     if (!IsRectSettledOnaPage(_screensContainer.localPosition))
  30.                     {
  31.                         ScrollToClosestElement();
  32.                     }
  33.                 }
  34.                 return;
  35.             }
  36.             else if (_lerp)
  37.             {
  38.                 _screensContainer.localPosition = Vector3.Lerp(_screensContainer.localPosition, _lerp_target, transitionSpeed * Time.deltaTime);
  39.                 if (Vector3.Distance(_screensContainer.localPosition, _lerp_target) < 0.1f)
  40.                 {
  41.                     _screensContainer.localPosition = _lerp_target;
  42.                     _lerp = false;
  43.                     EndScreenChange();
  44.                 }
  45.             }
  46.  
  47.             CurrentPage = GetPageforPosition(_screensContainer.localPosition);
  48.  
  49.             //If the container is moving check if it needs to settle on a page
  50.             if (!_pointerDown)
  51.             {
  52.                 if (_scroll_rect.velocity.x > 0.01 || _scroll_rect.velocity.x < -0.01)
  53.                 {
  54.                     //if the pointer is released and is moving slower than the threshold, then just land on a page
  55.                     if (IsRectMovingSlowerThanThreshold(0))
  56.                     {
  57.                         ScrollToClosestElement();
  58.                     }
  59.                 }
  60.             }
  61.         }
  62.  
  63.         private bool IsRectMovingSlowerThanThreshold(float startingSpeed)
  64.         {
  65.             return (_scroll_rect.velocity.x > startingSpeed && _scroll_rect.velocity.x < SwipeVelocityThreshold) ||
  66.                                 (_scroll_rect.velocity.x < startingSpeed && _scroll_rect.velocity.x > -SwipeVelocityThreshold);
  67.         }
  68.  
  69.         private void DistributePages()
  70.         {
  71.             _screens = _screensContainer.childCount;
  72.             _scroll_rect.horizontalNormalizedPosition = 0;
  73.  
  74.             int _offset = 0;
  75.             float _dimension = 0;
  76.             float currentXPosition = 0;
  77.             var pageStepValue = _childSize = (int)panelDimensions.width * ((PageStep == 0) ? 3 : PageStep);
  78.  
  79.  
  80.             for (int i = 0; i < _screensContainer.transform.childCount; i++)
  81.             {
  82.                 RectTransform child = _screensContainer.transform.GetChild(i).gameObject.GetComponent<RectTransform>();
  83.                 currentXPosition = _offset + (int)(i * pageStepValue);
  84.                 child.sizeDelta = new Vector2(panelDimensions.width, panelDimensions.height);
  85.                 child.anchoredPosition = new Vector2(currentXPosition, 0f);
  86.                 child.anchorMin = child.anchorMax = child.pivot = _childAnchorPoint;
  87.             }
  88.  
  89.             _dimension = currentXPosition + _offset * -1;
  90.  
  91.             _screensContainer.offsetMax = new Vector2(_dimension, 0f);
  92.         }
  93.  
  94.         /// <summary>
  95.         /// Add a new child to this Scroll Snap and recalculate it's children
  96.         /// </summary>
  97.         /// <param name="GO">GameObject to add to the ScrollSnap</param>
  98.         public void AddChild(GameObject GO)
  99.         {
  100.             AddChild(GO, false);
  101.         }
  102.  
  103.         /// <summary>
  104.         /// Add a new child to this Scroll Snap and recalculate it's children
  105.         /// </summary>
  106.         /// <param name="GO">GameObject to add to the ScrollSnap</param>
  107.         /// <param name="WorldPositionStays">Should the world position be updated to it's parent transform?</param>
  108.         public void AddChild(GameObject GO, bool WorldPositionStays)
  109.         {
  110.             _scroll_rect.horizontalNormalizedPosition = 0;
  111.             GO.transform.SetParent(_screensContainer, WorldPositionStays);
  112.             InitialiseChildObjectsFromScene();
  113.             DistributePages();
  114.             if (MaskArea) UpdateVisible();
  115.  
  116.             SetScrollContainerPosition();
  117.         }
  118.  
  119.         /// <summary>
  120.         /// Remove a new child to this Scroll Snap and recalculate it's children
  121.         /// *Note, this is an index address (0-x)
  122.         /// </summary>
  123.         /// <param name="index">Index element of child to remove</param>
  124.         /// <param name="ChildRemoved">Resulting removed GO</param>
  125.         public void RemoveChild(int index, out GameObject ChildRemoved)
  126.         {
  127.             RemoveChild(index, false, out ChildRemoved);
  128.         }
  129.  
  130.         /// <summary>
  131.         /// Remove a new child to this Scroll Snap and recalculate it's children
  132.         /// *Note, this is an index address (0-x)
  133.         /// </summary>
  134.         /// <param name="index">Index element of child to remove</param>
  135.         /// <param name="WorldPositionStays">If true, the parent-relative position, scale and rotation are modified such that the object keeps the same world space position, rotation and scale as before</param>
  136.         /// <param name="ChildRemoved">Resulting removed GO</param>
  137.         public void RemoveChild(int index, bool WorldPositionStays, out GameObject ChildRemoved)
  138.         {
  139.             ChildRemoved = null;
  140.             if (index < 0 || index > _screensContainer.childCount)
  141.             {
  142.                 return;
  143.             }
  144.             _scroll_rect.horizontalNormalizedPosition = 0;
  145.  
  146.             Transform child = _screensContainer.transform.GetChild(index);
  147.             child.SetParent(null, WorldPositionStays);
  148.             ChildRemoved = child.gameObject;
  149.             InitialiseChildObjectsFromScene();
  150.             DistributePages();
  151.             if (MaskArea) UpdateVisible();
  152.  
  153.             if (_currentPage > _screens - 1)
  154.             {
  155.                 CurrentPage = _screens - 1;
  156.             }
  157.  
  158.             SetScrollContainerPosition();
  159.         }
  160.  
  161.         /// <summary>
  162.         /// Remove all children from this ScrollSnap
  163.         /// </summary>
  164.         /// <param name="ChildrenRemoved">Array of child GO's removed</param>
  165.         public void RemoveAllChildren(out GameObject[] ChildrenRemoved)
  166.         {
  167.             RemoveAllChildren(false, out ChildrenRemoved);
  168.         }
  169.  
  170.         /// <summary>
  171.         /// Remove all children from this ScrollSnap
  172.         /// </summary>
  173.         /// <param name="WorldPositionStays">If true, the parent-relative position, scale and rotation are modified such that the object keeps the same world space position, rotation and scale as before</param>
  174.         /// <param name="ChildrenRemoved">Array of child GO's removed</param>
  175.         public void RemoveAllChildren(bool WorldPositionStays, out GameObject[] ChildrenRemoved)
  176.         {
  177.             var _screenCount = _screensContainer.childCount;
  178.             ChildrenRemoved = new GameObject[_screenCount];
  179.  
  180.             for (int i = _screenCount - 1; i >= 0; i--)
  181.             {
  182.                 ChildrenRemoved[i] = _screensContainer.GetChild(i).gameObject;
  183.                 ChildrenRemoved[i].transform.SetParent(null, WorldPositionStays);
  184.             }
  185.  
  186.             _scroll_rect.horizontalNormalizedPosition = 0;
  187.             CurrentPage = 0;
  188.             ResetAll ();
  189.             InitialiseChildObjectsFromScene();
  190.             DistributePages();
  191.             if (MaskArea) UpdateVisible();
  192.         }
  193.         /// <summary>
  194.         /// ////////////////////////////////
  195.         /// fix
  196.         /// </summary>
  197.         public void ResetAll(){
  198.             _currentPage = StartingScreen;
  199.             _screensContainer.offsetMin = new Vector2 (0,0);
  200.             UpdateLayout();
  201.         }
  202.  
  203.         private void SetScrollContainerPosition()
  204.         {
  205.             _scrollStartPosition = _screensContainer.localPosition.x;
  206.             _scroll_rect.horizontalNormalizedPosition = (float)(_currentPage) / (_screens - 1);
  207.             OnCurrentScreenChange(_currentPage);
  208.         }
  209.  
  210.         /// <summary>
  211.         /// used for changing / updating between screen resolutions
  212.         /// </summary>
  213.         public void UpdateLayout()
  214.         {
  215.             _lerp = false;
  216.             DistributePages();
  217.             if (MaskArea) UpdateVisible();
  218.             SetScrollContainerPosition();
  219.             OnCurrentScreenChange(_currentPage);
  220.         }
  221.  
  222.         private void OnRectTransformDimensionsChange()
  223.         {
  224.             if (_childAnchorPoint != Vector2.zero)
  225.             {
  226.                 UpdateLayout();
  227.             }
  228.         }
  229.  
  230.         private void OnEnable()
  231.         {
  232.             InitialiseChildObjectsFromScene();
  233.             DistributePages();
  234.             if (MaskArea) UpdateVisible();
  235.  
  236.             if (JumpOnEnable || !RestartOnEnable) SetScrollContainerPosition();
  237.             if (RestartOnEnable) GoToScreen(StartingScreen);
  238.         }
  239.  
  240.         #region Interfaces
  241.         /// <summary>
  242.         /// Release screen to swipe
  243.         /// </summary>
  244.         /// <param name="eventData"></param>
  245.         public void OnEndDrag(PointerEventData eventData)
  246.         {
  247.             _pointerDown = false;
  248.  
  249.             if (_scroll_rect.horizontal)
  250.             {
  251.                 var distance = Vector3.Distance(_startPosition, _screensContainer.localPosition);
  252.                 if (UseFastSwipe && distance < panelDimensions.width && distance >= FastSwipeThreshold)
  253.                 {
  254.                     _scroll_rect.velocity = Vector3.zero;
  255.                     if (_startPosition.x - _screensContainer.localPosition.x > 0)
  256.                     {
  257.                         NextScreen();
  258.                     }
  259.                     else
  260.                     {
  261.                         PreviousScreen();
  262.                     }
  263.                 }
  264.             }
  265.         }
  266.         #endregion
  267.     }
  268. }
Advertisement
Add Comment
Please, Sign In to add comment