FM/Assets/Scripts/Runtime/UI/Other/CarouselImage.cs

89 lines
2.9 KiB
C#
Raw Normal View History

2025-07-02 10:24:01 +08:00
using System;
using UnityEngine;
using UnityEngine.UI;
namespace Runtime
{
public class CarouselImage : MonoBehaviour
{
public CarouselImageItem pfb;
Sprite[] sprites;
CarouselImageItem[] buttons;
int currentIndex;
readonly Vector2 leftPos = new Vector2(-165, 0);
readonly Vector2 centerPos = new Vector2(0, 0);
readonly Vector2 rightPos = new Vector2(165, 0);
Vector3 bigSize = Vector3.one;
Vector3 smallSize = new Vector3(0.7f, 0.7f, 0.7f);
public Action<int> ClickAction;
public void Init(Sprite[] sprites, int index)
{
buttons = new CarouselImageItem[sprites.Length];
this.sprites = sprites;
this.currentIndex = index;
for (var i = 0; i < this.sprites.Length; i++)
{
var sprite = this.sprites[i];
var o = GameObject.Instantiate(pfb, this.transform);
o.GetComponent<Image>().sprite = sprite;
buttons[i] = o;
int themId = i;
o.Button.onClick.AddListener(() => { Carousel(themId); });
}
ResetAll(index);
}
public void ResetAll(int centerIndex)
{
currentIndex = centerIndex;
foreach (CarouselImageItem button in buttons)
{
button.Hide();
}
if (centerIndex - 1 >= 0)
buttons[centerIndex - 1].AppearAtPos(leftPos, smallSize);
buttons[centerIndex].AppearAtPos(centerPos, bigSize);
if (centerIndex + 1 < buttons.Length)
buttons[centerIndex + 1].AppearAtPos(rightPos, smallSize);
}
void Carousel(int i)
{
if (currentIndex == i)
return;
ClickAction?.Invoke(i);
if (i < currentIndex)
{
if (currentIndex - 1 >= 0)
buttons[currentIndex - 1].MoveToPos(centerPos, bigSize);
buttons[currentIndex].MoveToPos(rightPos, smallSize);
if (currentIndex + 1 < buttons.Length)
buttons[currentIndex + 1].Disappear();
if (currentIndex - 2 >= 0)
buttons[currentIndex - 2].AppearAtPos(leftPos, smallSize);
Debug.Log("click to left");
}
else
{
if (currentIndex - 1 >= 0)
buttons[currentIndex - 1].Disappear();
buttons[currentIndex].MoveToPos(leftPos, smallSize);
if (currentIndex + 1 < buttons.Length)
buttons[currentIndex + 1].MoveToPos(centerPos, bigSize);
if (currentIndex + 2 < buttons.Length)
buttons[currentIndex + 2].AppearAtPos(rightPos, smallSize);
Debug.Log("click to right");
}
currentIndex = i;
}
}
}