Scroller.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. /// Credit setchi (https://github.com/setchi)
  2. /// Sourced from - https://github.com/setchi/FancyScrollView
  3. using System;
  4. using UnityEngine.EventSystems;
  5. using UnityEngine.UI.Extensions.EasingCore;
  6. namespace UnityEngine.UI.Extensions
  7. {
  8. /// <summary>
  9. /// スクロール位置の制御を行うコンポーネント.
  10. /// </summary>
  11. public class Scroller : UIBehaviour, IPointerUpHandler, IPointerDownHandler, IBeginDragHandler, IEndDragHandler, IDragHandler, IScrollHandler
  12. {
  13. [SerializeField] RectTransform viewport = default;
  14. /// <summary>
  15. /// ビューポートのサイズ.
  16. /// </summary>
  17. public float ViewportSize => scrollDirection == ScrollDirection.Horizontal
  18. ? viewport.rect.size.x
  19. : viewport.rect.size.y;
  20. [SerializeField] ScrollDirection scrollDirection = ScrollDirection.Vertical;
  21. /// <summary>
  22. /// スクロール方向.
  23. /// </summary>
  24. public ScrollDirection ScrollDirection => scrollDirection;
  25. [SerializeField] MovementType movementType = MovementType.Elastic;
  26. /// <summary>
  27. /// コンテンツがスクロール範囲を越えて移動するときに使用する挙動.
  28. /// </summary>
  29. public MovementType MovementType
  30. {
  31. get => movementType;
  32. set => movementType = value;
  33. }
  34. [SerializeField] float elasticity = 0.1f;
  35. /// <summary>
  36. /// コンテンツがスクロール範囲を越えて移動するときに使用する弾力性の量.
  37. /// </summary>
  38. public float Elasticity
  39. {
  40. get => elasticity;
  41. set => elasticity = value;
  42. }
  43. [SerializeField] float scrollSensitivity = 1f;
  44. /// <summary>
  45. /// <see cref="ViewportSize"/> の端から端まで Drag したときのスクロール位置の変化量.
  46. /// </summary>
  47. public float ScrollSensitivity
  48. {
  49. get => scrollSensitivity;
  50. set => scrollSensitivity = value;
  51. }
  52. [SerializeField] bool inertia = true;
  53. /// <summary>
  54. /// 慣性を使用するかどうか. <c>true</c> を指定すると慣性が有効に, <c>false</c> を指定すると慣性が無効になります.
  55. /// </summary>
  56. public bool Inertia
  57. {
  58. get => inertia;
  59. set => inertia = value;
  60. }
  61. [SerializeField] float decelerationRate = 0.03f;
  62. /// <summary>
  63. /// スクロールの減速率. <see cref="Inertia"/> が <c>true</c> の場合のみ有効です.
  64. /// </summary>
  65. public float DecelerationRate
  66. {
  67. get => decelerationRate;
  68. set => decelerationRate = value;
  69. }
  70. [SerializeField] Snap snap = new Snap {
  71. Enable = true,
  72. VelocityThreshold = 0.5f,
  73. Duration = 0.3f,
  74. Easing = Ease.InOutCubic
  75. };
  76. /// <summary>
  77. /// <c>true</c> ならスナップし, <c>false</c>ならスナップしません.
  78. /// </summary>
  79. /// <remarks>
  80. /// スナップを有効にすると, 慣性でスクロールが止まる直前に最寄りのセルへ移動します.
  81. /// </remarks>
  82. public bool SnapEnabled
  83. {
  84. get => snap.Enable;
  85. set => snap.Enable = value;
  86. }
  87. [SerializeField] bool draggable = true;
  88. /// <summary>
  89. /// Drag 入力を受付けるかどうか.
  90. /// </summary>
  91. public bool Draggable
  92. {
  93. get => draggable;
  94. set => draggable = value;
  95. }
  96. [SerializeField] Scrollbar scrollbar = default;
  97. /// <summary>
  98. /// スクロールバーのオブジェクト.
  99. /// </summary>
  100. public Scrollbar Scrollbar => scrollbar;
  101. /// <summary>
  102. /// 現在のスクロール位置.
  103. /// </summary>
  104. /// <value></value>
  105. public float Position
  106. {
  107. get => currentPosition;
  108. set
  109. {
  110. autoScrollState.Reset();
  111. velocity = 0f;
  112. dragging = false;
  113. UpdatePosition(value);
  114. }
  115. }
  116. readonly AutoScrollState autoScrollState = new AutoScrollState();
  117. Action<float> onValueChanged;
  118. Action<int> onSelectionChanged;
  119. Vector2 beginDragPointerPosition;
  120. float scrollStartPosition;
  121. float prevPosition;
  122. float currentPosition;
  123. int totalCount;
  124. bool hold;
  125. bool scrolling;
  126. bool dragging;
  127. float velocity;
  128. [Serializable]
  129. class Snap
  130. {
  131. public bool Enable;
  132. public float VelocityThreshold;
  133. public float Duration;
  134. public Ease Easing;
  135. }
  136. static readonly EasingFunction DefaultEasingFunction = Easing.Get(Ease.OutCubic);
  137. class AutoScrollState
  138. {
  139. public bool Enable;
  140. public bool Elastic;
  141. public float Duration;
  142. public EasingFunction EasingFunction;
  143. public float StartTime;
  144. public float EndPosition;
  145. public Action OnComplete;
  146. public void Reset()
  147. {
  148. Enable = false;
  149. Elastic = false;
  150. Duration = 0f;
  151. StartTime = 0f;
  152. EasingFunction = DefaultEasingFunction;
  153. EndPosition = 0f;
  154. OnComplete = null;
  155. }
  156. public void Complete()
  157. {
  158. OnComplete?.Invoke();
  159. Reset();
  160. }
  161. }
  162. protected override void Start()
  163. {
  164. base.Start();
  165. if (scrollbar)
  166. {
  167. scrollbar.onValueChanged.AddListener(x => UpdatePosition(x * (totalCount - 1f), false));
  168. }
  169. }
  170. /// <summary>
  171. /// スクロール位置が変化したときのコールバックを設定します.
  172. /// </summary>
  173. /// <param name="callback">スクロール位置が変化したときのコールバック.</param>
  174. public void OnValueChanged(Action<float> callback) => onValueChanged = callback;
  175. /// <summary>
  176. /// 選択位置が変化したときのコールバックを設定します.
  177. /// </summary>
  178. /// <param name="callback">選択位置が変化したときのコールバック.</param>
  179. public void OnSelectionChanged(Action<int> callback) => onSelectionChanged = callback;
  180. /// <summary>
  181. /// アイテムの総数を設定します.
  182. /// </summary>
  183. /// <remarks>
  184. /// <paramref name="totalCount"/> を元に最大スクロール位置を計算します.
  185. /// </remarks>
  186. /// <param name="totalCount">アイテムの総数.</param>
  187. public void SetTotalCount(int totalCount) => this.totalCount = totalCount;
  188. /// <summary>
  189. /// 指定した位置まで移動します.
  190. /// </summary>
  191. /// <param name="position">スクロール位置. <c>0f</c> ~ <c>totalCount - 1f</c> の範囲.</param>
  192. /// <param name="duration">移動にかける秒数.</param>
  193. /// <param name="onComplete">移動が完了した際に呼び出されるコールバック.</param>
  194. public void ScrollTo(float position, float duration, Action onComplete = null) => ScrollTo(position, duration, Ease.OutCubic, onComplete);
  195. /// <summary>
  196. /// 指定した位置まで移動します.
  197. /// </summary>
  198. /// <param name="position">スクロール位置. <c>0f</c> ~ <c>totalCount - 1f</c> の範囲.</param>
  199. /// <param name="duration">移動にかける秒数.</param>
  200. /// <param name="easing">移動に使用するイージング.</param>
  201. /// <param name="onComplete">移動が完了した際に呼び出されるコールバック.</param>
  202. public void ScrollTo(float position, float duration, Ease easing, Action onComplete = null) => ScrollTo(position, duration, Easing.Get(easing), onComplete);
  203. /// <summary>
  204. /// 指定した位置まで移動します.
  205. /// </summary>
  206. /// <param name="position">スクロール位置. <c>0f</c> ~ <c>totalCount - 1f</c> の範囲.</param>
  207. /// <param name="duration">移動にかける秒数.</param>
  208. /// <param name="easingFunction">移動に使用するイージング関数.</param>
  209. /// <param name="onComplete">移動が完了した際に呼び出されるコールバック.</param>
  210. public void ScrollTo(float position, float duration, EasingFunction easingFunction, Action onComplete = null)
  211. {
  212. if (duration <= 0f)
  213. {
  214. Position = CircularPosition(position, totalCount);
  215. onComplete?.Invoke();
  216. return;
  217. }
  218. autoScrollState.Reset();
  219. autoScrollState.Enable = true;
  220. autoScrollState.Duration = duration;
  221. autoScrollState.EasingFunction = easingFunction ?? DefaultEasingFunction;
  222. autoScrollState.StartTime = Time.unscaledTime;
  223. autoScrollState.EndPosition = currentPosition + CalculateMovementAmount(currentPosition, position);
  224. autoScrollState.OnComplete = onComplete;
  225. velocity = 0f;
  226. scrollStartPosition = currentPosition;
  227. UpdateSelection(Mathf.RoundToInt(CircularPosition(autoScrollState.EndPosition, totalCount)));
  228. }
  229. /// <summary>
  230. /// 指定したインデックスの位置までジャンプします.
  231. /// </summary>
  232. /// <param name="index">アイテムのインデックス.</param>
  233. public void JumpTo(int index)
  234. {
  235. if (index < 0 || index > totalCount - 1)
  236. {
  237. throw new ArgumentOutOfRangeException(nameof(index));
  238. }
  239. UpdateSelection(index);
  240. Position = index;
  241. }
  242. /// <summary>
  243. /// <paramref name="sourceIndex"/> から <paramref name="destIndex"/> に移動する際の移動方向を返します.
  244. /// スクロール範囲が無制限に設定されている場合は, 最短距離の移動方向を返します.
  245. /// </summary>
  246. /// <param name="sourceIndex">移動元のインデックス.</param>
  247. /// <param name="destIndex">移動先のインデックス.</param>
  248. /// <returns></returns>
  249. public MovementDirection GetMovementDirection(int sourceIndex, int destIndex)
  250. {
  251. var movementAmount = CalculateMovementAmount(sourceIndex, destIndex);
  252. return scrollDirection == ScrollDirection.Horizontal
  253. ? movementAmount > 0
  254. ? MovementDirection.Left
  255. : MovementDirection.Right
  256. : movementAmount > 0
  257. ? MovementDirection.Up
  258. : MovementDirection.Down;
  259. }
  260. /// <inheritdoc/>
  261. void IPointerDownHandler.OnPointerDown(PointerEventData eventData)
  262. {
  263. if (!draggable || eventData.button != PointerEventData.InputButton.Left)
  264. {
  265. return;
  266. }
  267. hold = true;
  268. velocity = 0f;
  269. autoScrollState.Reset();
  270. }
  271. /// <inheritdoc/>
  272. void IPointerUpHandler.OnPointerUp(PointerEventData eventData)
  273. {
  274. if (!draggable || eventData.button != PointerEventData.InputButton.Left)
  275. {
  276. return;
  277. }
  278. if (hold && snap.Enable)
  279. {
  280. UpdateSelection(Mathf.Clamp(Mathf.RoundToInt(currentPosition), 0, totalCount - 1));
  281. ScrollTo(Mathf.RoundToInt(currentPosition), snap.Duration, snap.Easing);
  282. }
  283. hold = false;
  284. }
  285. /// <inheritdoc/>
  286. void IScrollHandler.OnScroll(PointerEventData eventData)
  287. {
  288. if (!draggable)
  289. {
  290. return;
  291. }
  292. var delta = eventData.scrollDelta;
  293. // Down is positive for scroll events, while in UI system up is positive.
  294. delta.y *= -1;
  295. var scrollDelta = scrollDirection == ScrollDirection.Horizontal
  296. ? Mathf.Abs(delta.y) > Mathf.Abs(delta.x)
  297. ? delta.y
  298. : delta.x
  299. : Mathf.Abs(delta.x) > Mathf.Abs(delta.y)
  300. ? delta.x
  301. : delta.y;
  302. if (eventData.IsScrolling())
  303. {
  304. scrolling = true;
  305. }
  306. var position = currentPosition + scrollDelta / ViewportSize * scrollSensitivity;
  307. if (movementType == MovementType.Clamped)
  308. {
  309. position += CalculateOffset(position);
  310. }
  311. if (autoScrollState.Enable)
  312. {
  313. autoScrollState.Reset();
  314. }
  315. UpdatePosition(position);
  316. }
  317. /// <inheritdoc/>
  318. void IBeginDragHandler.OnBeginDrag(PointerEventData eventData)
  319. {
  320. if (!draggable || eventData.button != PointerEventData.InputButton.Left)
  321. {
  322. return;
  323. }
  324. hold = false;
  325. RectTransformUtility.ScreenPointToLocalPointInRectangle(
  326. viewport,
  327. eventData.position,
  328. eventData.pressEventCamera,
  329. out beginDragPointerPosition);
  330. scrollStartPosition = currentPosition;
  331. dragging = true;
  332. autoScrollState.Reset();
  333. }
  334. /// <inheritdoc/>
  335. void IDragHandler.OnDrag(PointerEventData eventData)
  336. {
  337. if (!draggable || eventData.button != PointerEventData.InputButton.Left || !dragging)
  338. {
  339. return;
  340. }
  341. if (!RectTransformUtility.ScreenPointToLocalPointInRectangle(
  342. viewport,
  343. eventData.position,
  344. eventData.pressEventCamera,
  345. out var dragPointerPosition))
  346. {
  347. return;
  348. }
  349. var pointerDelta = dragPointerPosition - beginDragPointerPosition;
  350. var position = (scrollDirection == ScrollDirection.Horizontal ? -pointerDelta.x : pointerDelta.y)
  351. / ViewportSize
  352. * scrollSensitivity
  353. + scrollStartPosition;
  354. var offset = CalculateOffset(position);
  355. position += offset;
  356. if (movementType == MovementType.Elastic)
  357. {
  358. if (offset != 0f)
  359. {
  360. position -= RubberDelta(offset, scrollSensitivity);
  361. }
  362. }
  363. UpdatePosition(position);
  364. }
  365. /// <inheritdoc/>
  366. void IEndDragHandler.OnEndDrag(PointerEventData eventData)
  367. {
  368. if (!draggable || eventData.button != PointerEventData.InputButton.Left)
  369. {
  370. return;
  371. }
  372. dragging = false;
  373. }
  374. float CalculateOffset(float position)
  375. {
  376. if (movementType == MovementType.Unrestricted)
  377. {
  378. return 0f;
  379. }
  380. if (position < 0f)
  381. {
  382. return -position;
  383. }
  384. if (position > totalCount - 1)
  385. {
  386. return totalCount - 1 - position;
  387. }
  388. return 0f;
  389. }
  390. void UpdatePosition(float position, bool updateScrollbar = true)
  391. {
  392. onValueChanged?.Invoke(currentPosition = position);
  393. if (scrollbar && updateScrollbar)
  394. {
  395. scrollbar.value = Mathf.Clamp01(position / Mathf.Max(totalCount - 1f, 1e-4f));
  396. }
  397. }
  398. void UpdateSelection(int index) => onSelectionChanged?.Invoke(index);
  399. float RubberDelta(float overStretching, float viewSize) =>
  400. (1 - 1 / (Mathf.Abs(overStretching) * 0.55f / viewSize + 1)) * viewSize * Mathf.Sign(overStretching);
  401. void Update()
  402. {
  403. var deltaTime = Time.unscaledDeltaTime;
  404. var offset = CalculateOffset(currentPosition);
  405. if (autoScrollState.Enable)
  406. {
  407. var position = 0f;
  408. if (autoScrollState.Elastic)
  409. {
  410. position = Mathf.SmoothDamp(currentPosition, currentPosition + offset, ref velocity,
  411. elasticity, Mathf.Infinity, deltaTime);
  412. if (Mathf.Abs(velocity) < 0.01f)
  413. {
  414. position = Mathf.Clamp(Mathf.RoundToInt(position), 0, totalCount - 1);
  415. velocity = 0f;
  416. autoScrollState.Complete();
  417. }
  418. }
  419. else
  420. {
  421. var alpha = Mathf.Clamp01((Time.unscaledTime - autoScrollState.StartTime) /
  422. Mathf.Max(autoScrollState.Duration, float.Epsilon));
  423. position = Mathf.LerpUnclamped(scrollStartPosition, autoScrollState.EndPosition,
  424. autoScrollState.EasingFunction(alpha));
  425. if (Mathf.Approximately(alpha, 1f))
  426. {
  427. autoScrollState.Complete();
  428. }
  429. }
  430. UpdatePosition(position);
  431. }
  432. else if (!(dragging || scrolling) && (!Mathf.Approximately(offset, 0f) || !Mathf.Approximately(velocity, 0f)))
  433. {
  434. var position = currentPosition;
  435. if (movementType == MovementType.Elastic && !Mathf.Approximately(offset, 0f))
  436. {
  437. autoScrollState.Reset();
  438. autoScrollState.Enable = true;
  439. autoScrollState.Elastic = true;
  440. UpdateSelection(Mathf.Clamp(Mathf.RoundToInt(position), 0, totalCount - 1));
  441. }
  442. else if (inertia)
  443. {
  444. velocity *= Mathf.Pow(decelerationRate, deltaTime);
  445. if (Mathf.Abs(velocity) < 0.001f)
  446. {
  447. velocity = 0f;
  448. }
  449. position += velocity * deltaTime;
  450. if (snap.Enable && Mathf.Abs(velocity) < snap.VelocityThreshold)
  451. {
  452. ScrollTo(Mathf.RoundToInt(currentPosition), snap.Duration, snap.Easing);
  453. }
  454. }
  455. else
  456. {
  457. velocity = 0f;
  458. }
  459. if (!Mathf.Approximately(velocity, 0f))
  460. {
  461. if (movementType == MovementType.Clamped)
  462. {
  463. offset = CalculateOffset(position);
  464. position += offset;
  465. if (Mathf.Approximately(position, 0f) || Mathf.Approximately(position, totalCount - 1f))
  466. {
  467. velocity = 0f;
  468. UpdateSelection(Mathf.RoundToInt(position));
  469. }
  470. }
  471. UpdatePosition(position);
  472. }
  473. }
  474. if (!autoScrollState.Enable && (dragging || scrolling) && inertia)
  475. {
  476. var newVelocity = (currentPosition - prevPosition) / deltaTime;
  477. velocity = Mathf.Lerp(velocity, newVelocity, deltaTime * 10f);
  478. }
  479. prevPosition = currentPosition;
  480. scrolling = false;
  481. }
  482. float CalculateMovementAmount(float sourcePosition, float destPosition)
  483. {
  484. if (movementType != MovementType.Unrestricted)
  485. {
  486. return Mathf.Clamp(destPosition, 0, totalCount - 1) - sourcePosition;
  487. }
  488. var amount = CircularPosition(destPosition, totalCount) - CircularPosition(sourcePosition, totalCount);
  489. if (Mathf.Abs(amount) > totalCount * 0.5f)
  490. {
  491. amount = Mathf.Sign(-amount) * (totalCount - Mathf.Abs(amount));
  492. }
  493. return amount;
  494. }
  495. float CircularPosition(float p, int size) => size < 1 ? 0 : p < 0 ? size - 1 + (p + 1) % size : p % size;
  496. }
  497. }