Scroller.cs 20 KB

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