99 lines
3.2 KiB
C#
99 lines
3.2 KiB
C#
using System;
|
|
using Base.Helper;
|
|
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(-130, 0);
|
|
readonly Vector2 centerPos = new Vector2(0, 0);
|
|
readonly Vector2 rightPos = new Vector2(130, 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);
|
|
var image = o.GetComponent<Image>();
|
|
image.sprite = sprite;
|
|
UIHelper.LimitTheImageSize(image, 160);
|
|
buttons[i] = o;
|
|
int themId = i;
|
|
o.Button.onClick.AddListener(() => { Carousel(themId); });
|
|
}
|
|
|
|
ResetAll(index);
|
|
}
|
|
|
|
private void OnDisable()
|
|
{
|
|
foreach (var item in buttons)
|
|
{
|
|
GameObject.Destroy(item.gameObject);
|
|
}
|
|
}
|
|
|
|
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;
|
|
}
|
|
}
|
|
} |