Posts Infinite Horizontal Scroll (무한 횡스크롤) UI
Post
Cancel

Infinite Horizontal Scroll (무한 횡스크롤) UI

Summary


  • 자식 UI들을 좌우로 무한히 스크롤시키는 컴포넌트


Preview


2021_0728_InfiniteScroll01

2021_0728_InfiniteScroll02


How To Use


  • 횡스크롤 시킬 UI들을 하나의 부모 오브젝트에 묶는다.

  • 해당 부모 오브젝트에 InfiniteHorizontalScroll 컴포넌트를 추가한다.

  • 게임 시작 후 좌우 화살표 키를 누르면 각 방향으로 스크롤이 진행된다.


Properties


Center UI Size (Vector2)

  • 중앙에 위치한 UI의 크기

Edge UI Size (Vector2)

  • 좌우 끝에 위치한 UI의 크기

Space Width (float)

  • 각 UI 사이의 간격

Transition Time (float)

  • 스크롤 한 번에 소요되는 시간(초)


Use Imposter (bool)

  • 스크롤 시 복제된 UI를 이용해 자연스러운 연출을 추가할지 여부

[1] true 2021_0728_InfiniteScroll_UseImposter

[2] false 2021_0728_InfiniteScroll_NotUseImposter


Download



Source Code


.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;

// 날짜 : 2021-07-28 AM 2:05:41
// 작성자 : Rito

namespace Rito
{
    /// <summary> 
    /// 무한 횡스크롤 UI
    /// </summary>
    public class InfiniteHorizontalScroll : MonoBehaviour
    {
        /***********************************************************************
        *                           Inspector Fields
        ***********************************************************************/
        #region .
        [SerializeField] private Vector2 centerUISize = new Vector2(200f, 200f);  // 중앙 UI의 크기
        [SerializeField] private Vector2 edgeUISize = new Vector2(100f, 100f);    // 가장 외곽 UI의 크기

        [Range(0f, 100f)]
        [SerializeField] private float spaceWidth = 25f; // 이미지 사이 간격

        [Range(0.01f, 2f)]
        [SerializeField] private float transitionTime = 0.5f; // 전환에 걸리는 시간

        [SerializeField] private bool useImposter = true; // 임포스터 사용 여부

        #endregion
        /***********************************************************************
        *                           Private Fields
        ***********************************************************************/
        #region .
        private const int LEFT = 1;
        private const int RIGHT = -1;

        private List<RectTransform> _targetList = new List<RectTransform>(8);
        private List<RectTransform> _imposterList = new List<RectTransform>(8);
        private int _targetCount;

        private RectTransform _currentImposter;

        [SerializeField]
        private int _currentIndex = 0;

        private bool _isTransiting = false;
        private float _progress; // 진행도 : 0 ~ 1
        private int _direction;

        #endregion
        /***********************************************************************
        *                           Look Up Tables
        ***********************************************************************/
        #region .
        private int _lookupCount;
        private int _lookupCenterIndex;

        private float[] _xPosTable; // 인덱스 위치에 따른 X 좌표 기록
        private Vector2[] _sizeTable; // 인덱스 위치에 따른 크기 기록

        private void GenerateLookUpTables()
        {
            _xPosTable = new float[_lookupCount];
            _sizeTable = new Vector2[_lookupCount];

            for (int i = 0; i < _lookupCount; i++)
            {
                _xPosTable[i] = GetXPosition(i);
                _sizeTable[i] = GetSize(i);
            }
        }

        /// <summary> lookup center index와의 인덱스 차이 계산 </summary>
        private int GetIndexDiffFromCenter(int index)
        {
            return Mathf.Abs(index - _lookupCenterIndex);
        }

        /// <summary> 가로세로 크기 구하기 </summary>
        private Vector2 GetSize(int lookupIndex)
        {
            if (lookupIndex == _lookupCenterIndex)
                return centerUISize;

            float absGap = GetIndexDiffFromCenter(lookupIndex);

            return Vector2.Lerp(centerUISize, edgeUISize, absGap / _lookupCenterIndex);
        }

        /// <summary> X좌표 구하기 </summary>
        private float GetXPosition(int lookupIndex)
        {
            // 중앙 위치
            if (lookupIndex == _lookupCenterIndex)
                return 0f;

            float absGap = GetIndexDiffFromCenter(lookupIndex);

            // // 1. 빈공간 합
            float pos = absGap * spaceWidth;

            // 2. 너비 합
            for (int i = 0; i <= absGap; i++)
            {
                float w = Vector2.Lerp(centerUISize, edgeUISize, i / (float)_lookupCenterIndex).x;

                if (0 < i && i < absGap)
                    pos += w;
                else
                    pos += w * 0.5f;
            }

            return (lookupIndex < _lookupCenterIndex) ? -pos : pos;
        }

        #endregion
        /***********************************************************************
        *                           Unity Events
        ***********************************************************************/
        #region .
        private void OnEnable()
        {
            _targetList.Clear();
            int childCount = transform.childCount;
            for (int i = 0; i < childCount; i++)
            {
                Transform child = transform.GetChild(i);
                GameObject go = child.gameObject;

                if (go.activeSelf == false) continue;
                if (go.hideFlags == HideFlags.HideInHierarchy) continue;

                _targetList.Add(child.GetComponent<RectTransform>());
            }

            _targetCount = _targetList.Count;
            _lookupCount = _targetCount + 2;
            _lookupCenterIndex = _lookupCount / 2;

            GenerateLookUpTables();
            InitRectTransforms();
            
            if (useImposter) GenerateImposters();
        }

        private void Update()
        {
            if (!_isTransiting)
            {
                if (Input.GetKeyDown(KeyCode.LeftArrow))
                {
                    _direction = LEFT;
                    Local_BeginTransition();
                }
                else if (Input.GetKeyDown(KeyCode.RightArrow))
                {
                    _direction = RIGHT;
                    Local_BeginTransition();
                }
            }
            else
            {
                _progress += Time.deltaTime / transitionTime;
                if (_progress > 1f) _progress = 1f;

                OnTransition();

                if (_progress == 1f)
                {
                    _isTransiting = false;
                    _currentIndex = (_currentIndex - _direction) % _targetCount;
                    if (_currentIndex < 0) _currentIndex += _targetCount;
                    OnTransitionEnd();
                }
            }

            void Local_BeginTransition()
            {
                _isTransiting = true;
                _progress = 0;
                OnTransitionBegin();
            }
        }

        private void OnTransitionBegin()
        {
            if (useImposter) InitImposter();
        }

        private void OnTransition()
        {
            MoveAll();
            if (useImposter) MoveImposter();
        }

        private void OnTransitionEnd()
        {
            for (int i = 0; i < _targetCount; i++)
            {
                int li = GetLookupIndex(i);

                // 양측의 이미지를 알맞은 위치로 이동
                if (li == 1 || li == _targetCount)
                {
                    _targetList[i].SetSizeAndXPosition(_sizeTable[li], _xPosTable[li]);
                }
            }

            // 임포스터 비활성화
            if (useImposter)
                _currentImposter.gameObject.SetActive(false);
        }
        #endregion
        /***********************************************************************
        *                           Getter Methods
        ***********************************************************************/
        #region .
        /// <summary> index를 lookup index에 매핑하기 </summary>
        private int GetLookupIndex(int index)
        {
            index = index - _currentIndex + _lookupCenterIndex;

            if (index > _targetCount)
                index -= _targetCount;

            else if (index <= 0)
                index += _targetCount;

            return index;
        }

        /// <summary> lookup index를 index에 매핑하기 </summary>
        private int GetIndexFromLookupIndex(int lookupIndex)
        {
            int index = lookupIndex - _lookupCenterIndex + _currentIndex;

            if (index < 0)
                index += _targetCount;

            return index % _targetCount;
        }

        /// <summary> 가장 좌측 이미지의 실제 인덱스 </summary>
        private int GetLeftImageIndex() => GetIndexFromLookupIndex(0);
        /// <summary> 가장 우측 이미지의 실제 인덱스 </summary>
        private int GetRightImageIndex() => GetIndexFromLookupIndex(_lookupCount - 1);

        #endregion
        /***********************************************************************
        *                           Rect Transform Methods
        ***********************************************************************/
        #region .
        /// <summary> Rect Transform X Pos, Size 초기 설정 </summary>
        private void InitRectTransforms()
        {
            for (int i = 0; i < _targetCount; i++)
            {
                int li = GetLookupIndex(i);
                float xPos = _xPosTable[li];
                Vector2 size = _sizeTable[li];

                _targetList[i].SetSizeAndXPosition(size, xPos);
            }
        }

        /// <summary> 모든 이미지의 Rect Transform 이동시키기 </summary>
        private void MoveAll()
        {
            for (int i = 0; i < _targetCount; i++)
            {
                int li = GetLookupIndex(i);

                float curXPos = _xPosTable[li];
                float nextXPos = _xPosTable[li + _direction];
                float xPos = Mathf.Lerp(curXPos, nextXPos, _progress);

                Vector2 curSize = _sizeTable[li];
                Vector2 nextSize = _sizeTable[li + _direction];
                Vector2 size = Vector2.Lerp(curSize, nextSize, _progress);
                _targetList[i].SetSizeAndXPosition(size, xPos);
            }
        }
        #endregion
        /***********************************************************************
        *                           Imposter Methods
        ***********************************************************************/
        #region .
        private void GenerateImposters()
        {
            _imposterList.Clear();

            for (int i = 0; i < _targetCount; i++)
            {
                GameObject go = Instantiate(_targetList[i].gameObject);
                go.transform.SetParent(transform);
                go.hideFlags = HideFlags.HideInHierarchy;

                RectTransform rt = go.GetComponent<RectTransform>();
                _imposterList.Add(rt);
                go.SetActive(false);
            }
        }

        private void InitImposter()
        {
            int index, lookupIndex;
            float xPos;
            Vector2 size;

            switch (_direction)
            {
                default:
                case LEFT:
                    index = GetLeftImageIndex();
                    lookupIndex = 0;
                    break;

                case RIGHT:
                    index = GetRightImageIndex();
                    lookupIndex = _lookupCount - 1;
                    break;
            }

            xPos = _xPosTable[lookupIndex];
            size = _sizeTable[lookupIndex];

            _currentImposter = _imposterList[index];
            _currentImposter.SetSizeAndXPosition(size, xPos);
            _currentImposter.gameObject.SetActive(true);
        }

        private void MoveImposter()
        {
            int lookupIndex, lookupIndexNext;

            switch (_direction)
            {
                default:
                case LEFT:
                    lookupIndex = 0;
                    lookupIndexNext = 1;
                    break;

                case RIGHT:
                    lookupIndex = _lookupCount - 1;
                    lookupIndexNext = _lookupCount - 2;
                    break;
            }

            float curXPos = _xPosTable[lookupIndex];
            float nextXPos = _xPosTable[lookupIndexNext];
            float xPos = Mathf.Lerp(curXPos, nextXPos, _progress);

            Vector2 curSize = _sizeTable[lookupIndex];
            Vector2 nextSize = _sizeTable[lookupIndexNext];
            Vector2 size = Vector2.Lerp(curSize, nextSize, _progress);

            _currentImposter.SetSizeAndXPosition(size, xPos);
        }
        #endregion
        /***********************************************************************
        *                           Public Methods
        ***********************************************************************/
        #region .
        /// <summary> 현재 선택된 UI의 인덱스 참조 </summary>
        public int GetCurrentIndex() => _currentIndex;
        #endregion
    }

    /***********************************************************************
    *                               Extension Helpers
    ***********************************************************************/
    #region .
    static class RectTransformExtensionHelper
    {
        public static void SetSizeAndXPosition(this RectTransform @this, in Vector2 size, float xPos)
        {
            @this.sizeDelta = size;
            @this.anchoredPosition = new Vector2(xPos, 0f);
        }
    }

    #endregion
}
This post is licensed under CC BY 4.0 by the author.