CustomListComponent.cs 13.7 KB
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 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
using UnityEngine;
using System.Collections.Generic;

public enum ScrollDirection
{
    Horizontal,
    Vertical
}

public enum LoopMode
{
    Normal,
    InfiniteLoop
}

public enum SnapMode
{
    Free,
    CenterAligned
}

public enum DragMode
{
    FixedDistance,
    MouseDistance
}

public enum EasingType
{
    Linear,
    EaseIn,
    EaseOut,
    EaseInOut
}

public class CustomListComponent : MonoBehaviour
{
    [Header("基本设置")] [SerializeField] private ScrollDirection direction = ScrollDirection.Horizontal;
    [SerializeField] private LoopMode loopMode = LoopMode.InfiniteLoop;
    [SerializeField] private SnapMode snapMode = SnapMode.CenterAligned;
    [SerializeField] private DragMode dragMode = DragMode.MouseDistance;
    [SerializeField] private EasingType easingType = EasingType.EaseOut;

    [Header("Item设置")] [SerializeField] private GameObject itemPrefab;
    [SerializeField] private float itemSize = 100f;
    [SerializeField] private float spacing = 20f;

    [Header("动画设置")] [SerializeField] private float snapSpeed = 5f;
    [SerializeField] private float dragSensitivity = 1f;
    [SerializeField] private float fixedDragDistance = 50f;

    [Header("数据")] [SerializeField] private List<ItemData> itemDataList = new List<ItemData>();

    private RectTransform rectTransform;
    private List<ItemInstance> activeItems = new List<ItemInstance>();
    private float viewportSize;
    private int maxVisibleItems;
    private float totalContentSize;
    private float currentPosition;
    private float targetPosition;
    private Vector2 lastMousePosition;
    private bool isDragging;
    private int centerItemIndex;
    private float dragStartTime;
    private float dragStartPosition;

    [System.Serializable]
    public class ItemData
    {
        public string id;
        public string name;
        public Sprite icon;
        public object data;
    }

    private class ItemInstance
    {
        public GameObject gameObject;
        public RectTransform rectTransform;
        public int dataIndex;
        public ItemUI itemUI;
    }

    public delegate void CenterItemChangedHandler(int index, ItemData data);

    public event CenterItemChangedHandler OnCenterItemChanged;

    private void Awake()
    {
        rectTransform = GetComponent<RectTransform>();
        CalculateViewportSize();
        CalculateMaxVisibleItems();
        InitializeItems();
    }

    private void CalculateViewportSize()
    {
        if (direction == ScrollDirection.Horizontal)
        {
            viewportSize = rectTransform.rect.width;
        }
        else
        {
            viewportSize = rectTransform.rect.height;
        }
    }

    private void CalculateMaxVisibleItems()
    {
        // 计算最多需要多少个Item才能铺满视口
        maxVisibleItems = Mathf.CeilToInt((viewportSize + spacing) / (itemSize + spacing)) + 2;
        Debug.Log($"最多可见Item数量: {maxVisibleItems}");
    }

    private void InitializeItems()
    {
        // 清除现有Item
        foreach (var item in activeItems)
        {
            Destroy(item.gameObject);
        }

        activeItems.Clear();

        // 创建必要的Item实例
        for (int i = 0; i < maxVisibleItems; i++)
        {
            GameObject itemGO = Instantiate(itemPrefab, transform);
            ItemInstance item = new ItemInstance
            {
                gameObject = itemGO,
                rectTransform = itemGO.GetComponent<RectTransform>(),
                dataIndex = i % itemDataList.Count,
                itemUI = itemGO.GetComponent<ItemUI>()
            };

            UpdateItemPosition(item, i);
            UpdateItemData(item);

            activeItems.Add(item);
        }

        // 计算总内容大小
        totalContentSize = itemDataList.Count * (itemSize + spacing) - spacing;

        // 初始化位置
        currentPosition = 0;
        targetPosition = 0;
        UpdateCenterItem();
    }

    private void UpdateItemPosition(ItemInstance item, int index)
    {
        float position = index * (itemSize + spacing);

        if (direction == ScrollDirection.Horizontal)
        {
            item.rectTransform.anchoredPosition = new Vector2(position - currentPosition, 0);
        }
        else
        {
            item.rectTransform.anchoredPosition = new Vector2(0, -(position - currentPosition));
        }
    }

    private void UpdateItemData(ItemInstance item)
    {
        if (item.itemUI != null && item.dataIndex < itemDataList.Count)
        {
            item.itemUI.SetData(itemDataList[item.dataIndex]);
        }
    }

    private void Update()
    {
        HandleInput();
        UpdateScrollPosition();
        UpdateItems();
    }

    private void HandleInput()
    {
        if (Input.GetMouseButtonDown(0))
        {
            if (RectTransformUtility.RectangleContainsScreenPoint(rectTransform, Input.mousePosition))
            {
                isDragging = true;
                lastMousePosition = Input.mousePosition;
                dragStartTime = Time.time;
                dragStartPosition = currentPosition;
            }
        }

        if (Input.GetMouseButtonUp(0))
        {
            if (isDragging)
            {
                isDragging = false;

                if (snapMode == SnapMode.CenterAligned)
                {
                    SnapToNearestItem();
                }
            }
        }

        if (isDragging)
        {
            Vector2 mouseDelta = Input.mousePosition - new Vector3(lastMousePosition.x, lastMousePosition.y, 0);
            lastMousePosition = Input.mousePosition;

            float dragAmount = direction == ScrollDirection.Horizontal ? mouseDelta.x : -mouseDelta.y;

            if (dragMode == DragMode.FixedDistance)
            {
                dragAmount = Mathf.Sign(dragAmount) * fixedDragDistance;
            }

            currentPosition -= dragAmount * dragSensitivity;

            // 处理边界
            if (loopMode == LoopMode.Normal)
            {
                currentPosition = Mathf.Clamp(currentPosition, 0, Mathf.Max(0, totalContentSize - viewportSize));
            }
        }
    }

    private void UpdateScrollPosition()
    {
        if (!isDragging && currentPosition != targetPosition)
        {
            float deltaTime = Time.deltaTime * snapSpeed;

            // 应用缓动函数
            switch (easingType)
            {
                case EasingType.Linear:
                    currentPosition = Mathf.Lerp(currentPosition, targetPosition, deltaTime);
                    break;
                case EasingType.EaseIn:
                    currentPosition = EaseIn(currentPosition, targetPosition, deltaTime);
                    break;
                case EasingType.EaseOut:
                    currentPosition = EaseOut(currentPosition, targetPosition, deltaTime);
                    break;
                case EasingType.EaseInOut:
                    currentPosition = EaseInOut(currentPosition, targetPosition, deltaTime);
                    break;
            }

            if (Mathf.Abs(currentPosition - targetPosition) < 0.1f)
            {
                currentPosition = targetPosition;
            }
        }
    }

    private void UpdateItems()
    {
        if (loopMode == LoopMode.InfiniteLoop)
        {
            // 处理无限循环
            foreach (var item in activeItems)
            {
                bool needsUpdate = false;

                if (direction == ScrollDirection.Horizontal)
                {
                    float itemPos = item.rectTransform.anchoredPosition.x + currentPosition;

                    // 如果Item超出左边界,移动到右侧
                    if (itemPos < -itemSize)
                    {
                        item.dataIndex = (item.dataIndex + activeItems.Count) % itemDataList.Count;
                        needsUpdate = true;
                    }
                    // 如果Item超出右边界,移动到左侧
                    else if (itemPos > viewportSize)
                    {
                        item.dataIndex = (item.dataIndex - activeItems.Count + itemDataList.Count) % itemDataList.Count;
                        needsUpdate = true;
                    }
                }
                else
                {
                    float itemPos = -(item.rectTransform.anchoredPosition.y - currentPosition);

                    // 如果Item超出上边界,移动到下侧
                    if (itemPos < -itemSize)
                    {
                        item.dataIndex = (item.dataIndex + activeItems.Count) % itemDataList.Count;
                        needsUpdate = true;
                    }
                    // 如果Item超出下边界,移动到上侧
                    else if (itemPos > viewportSize)
                    {
                        item.dataIndex = (item.dataIndex - activeItems.Count + itemDataList.Count) % itemDataList.Count;
                        needsUpdate = true;
                    }
                }

                if (needsUpdate)
                {
                    UpdateItemData(item);

                    // 重新计算位置
                    int virtualIndex = Mathf.FloorToInt(currentPosition / (itemSize + spacing));
                    virtualIndex = (virtualIndex + item.dataIndex) % itemDataList.Count;

                    UpdateItemPosition(item, virtualIndex);
                }
                else
                {
                    // 仅更新位置
                    UpdateItemPosition(item,
                        Mathf.FloorToInt((item.rectTransform.anchoredPosition.x + currentPosition) /
                                         (itemSize + spacing)));
                }
            }
        }

        UpdateCenterItem();
    }

    private void SnapToNearestItem()
    {
        if (itemDataList.Count == 0) return;

        // 计算最接近中心的Item
        float centerPos = viewportSize / 2;
        float closestDistance = float.MaxValue;
        int closestIndex = 0;

        foreach (var item in activeItems)
        {
            float itemPos = direction == ScrollDirection.Horizontal
                ? item.rectTransform.anchoredPosition.x + itemSize / 2
                : -(item.rectTransform.anchoredPosition.y - itemSize / 2);

            float distance = Mathf.Abs(itemPos - centerPos);

            if (distance < closestDistance)
            {
                closestDistance = distance;
                closestIndex = item.dataIndex;
            }
        }

        // 设置目标位置
        float targetPos = closestIndex * (itemSize + spacing);

        // 调整目标位置使选中的Item居中
        if (direction == ScrollDirection.Horizontal)
        {
            targetPos -= (viewportSize - itemSize) / 2;
        }
        else
        {
            targetPos -= (viewportSize - itemSize) / 2;
        }

        // 限制在边界内
        if (loopMode == LoopMode.Normal)
        {
            targetPos = Mathf.Clamp(targetPos, 0, Mathf.Max(0, totalContentSize - viewportSize));
        }

        targetPosition = targetPos;
    }

    private void UpdateCenterItem()
    {
        float centerPos = viewportSize / 2;
        float closestDistance = float.MaxValue;
        int newCenterIndex = -1;

        foreach (var item in activeItems)
        {
            float itemPos = direction == ScrollDirection.Horizontal
                ? item.rectTransform.anchoredPosition.x + itemSize / 2
                : -(item.rectTransform.anchoredPosition.y - itemSize / 2);

            float distance = Mathf.Abs(itemPos - centerPos);

            if (distance < closestDistance)
            {
                closestDistance = distance;
                newCenterIndex = item.dataIndex;
            }
        }

        if (newCenterIndex != centerItemIndex && newCenterIndex >= 0 && newCenterIndex < itemDataList.Count)
        {
            centerItemIndex = newCenterIndex;
            OnCenterItemChanged?.Invoke(centerItemIndex, itemDataList[centerItemIndex]);
        }
    }

    // 缓动函数
    private float EaseIn(float start, float end, float value)
    {
        end -= start;
        return end * Mathf.Pow(value, 2) + start;
    }

    private float EaseOut(float start, float end, float value)
    {
        end -= start;
        return -end * value * (value - 2) + start;
    }

    private float EaseInOut(float start, float end, float value)
    {
        value /= 0.5f;
        end -= start;

        if (value < 1)
        {
            return end * 0.5f * Mathf.Pow(value, 2) + start;
        }

        value--;
        return -end * 0.5f * (value * (value - 2) - 1) + start;
    }

    // 公共方法
    public void SetDirection(ScrollDirection newDirection)
    {
        direction = newDirection;
        CalculateViewportSize();
        InitializeItems();
    }

    public void SetLoopMode(LoopMode newMode)
    {
        loopMode = newMode;
    }

    public void SetSnapMode(SnapMode newMode)
    {
        snapMode = newMode;
    }

    public void SetDragMode(DragMode newMode)
    {
        dragMode = newMode;
    }

    public void SetEasingType(EasingType newType)
    {
        easingType = newType;
    }

    public void SetItemSize(float size)
    {
        itemSize = size;
        CalculateMaxVisibleItems();
        InitializeItems();
    }

    public void SetSpacing(float newSpacing)
    {
        spacing = newSpacing;
        CalculateMaxVisibleItems();
        InitializeItems();
    }

    public void SetItemData(List<ItemData> dataList)
    {
        itemDataList = dataList;
        CalculateMaxVisibleItems();
        InitializeItems();
    }

    public ItemData GetCenterItemData()
    {
        if (centerItemIndex >= 0 && centerItemIndex < itemDataList.Count)
        {
            return itemDataList[centerItemIndex];
        }

        return null;
    }
}