4using System.Collections;
9 [RequireComponent(typeof(ScrollRect))]
10 [AddComponentMenu(
"UI/Extensions/ScrollRectTweener")]
14 ScrollRect scrollRect;
26 scrollRect = GetComponent<ScrollRect>();
27 wasHorizontal = scrollRect.horizontal;
28 wasVertical = scrollRect.vertical;
33 Scroll(
new Vector2(normalizedX, scrollRect.verticalNormalizedPosition));
38 Scroll(
new Vector2(normalizedX, scrollRect.verticalNormalizedPosition), duration);
43 Scroll(
new Vector2(scrollRect.horizontalNormalizedPosition, normalizedY));
48 Scroll(
new Vector2(scrollRect.horizontalNormalizedPosition, normalizedY), duration);
51 public void Scroll(Vector2 normalizedPos)
53 Scroll(normalizedPos, GetScrollDuration(normalizedPos));
56 float GetScrollDuration(Vector2 normalizedPos)
58 Vector2 currentPos = GetCurrentPos();
59 return Vector2.Distance(DeNormalize(currentPos), DeNormalize(normalizedPos)) /
moveSpeed;
62 Vector2 DeNormalize(Vector2 normalizedPos)
64 return new Vector2(normalizedPos.x * scrollRect.content.rect.width, normalizedPos.y * scrollRect.content.rect.height);
67 Vector2 GetCurrentPos()
69 return new Vector2(scrollRect.horizontalNormalizedPosition, scrollRect.verticalNormalizedPosition);
72 public void Scroll(Vector2 normalizedPos,
float duration)
74 startPos = GetCurrentPos();
75 targetPos = normalizedPos;
81 StartCoroutine(DoMove(duration));
84 IEnumerator DoMove(
float duration)
91 Vector2 posOffset = targetPos - startPos;
93 float currentTime = 0f;
94 while (currentTime < duration)
96 currentTime += Time.deltaTime;
97 scrollRect.normalizedPosition =
EaseVector(currentTime, startPos, posOffset, duration);
101 scrollRect.normalizedPosition = targetPos;
104 RestoreScrollability();
107 public Vector2
EaseVector(
float currentTime, Vector2 startValue, Vector2 changeInValue,
float duration)
110 changeInValue.x * Mathf.Sin(currentTime / duration * (Mathf.PI / 2)) + startValue.x,
111 changeInValue.y * Mathf.Sin(currentTime / duration * (Mathf.PI / 2)) + startValue.y
115 public void OnDrag(PointerEventData eventData)
125 RestoreScrollability();
128 void LockScrollability()
130 scrollRect.horizontal =
false;
131 scrollRect.vertical =
false;
134 void RestoreScrollability()
136 scrollRect.horizontal = wasHorizontal;
137 scrollRect.vertical = wasVertical;
Credit Erdener Gonenc - @PixelEnvision.