MiniGames/Assets/ZibuSlotMachine2/Scripts/InfiniteScrollSnap.cs

74 lines
2.1 KiB
C#
Raw Permalink Normal View History

2025-07-22 01:18:44 +05:00
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class InfiniteScrollSnap : MonoBehaviour {
public ScrollRect scrollRect;
public RectTransform content;
public float itemWidth = 200f;
public float snapSpeed = 10f;
public List<ZibuPiece> pieces;
public List<Sprite> zibuSprites;
private bool isDragging = false;
private float targetX;
private int centerIndex = 0;
void Update() {
float contentX = content.anchoredPosition.x;
foreach (var piece in pieces) {
Vector3 localPos = piece.transform.localPosition;
if (localPos.x + contentX < -itemWidth * 3) {
MoveRight(piece);
} else if (localPos.x + contentX > itemWidth * 3) {
MoveLeft(piece);
}
}
if (!isDragging) {
Vector2 pos = content.anchoredPosition;
float newX = Mathf.Lerp(pos.x, targetX, Time.deltaTime * snapSpeed);
content.anchoredPosition = new Vector2(newX, pos.y);
}
}
public void OnBeginDrag() {
isDragging = true;
}
public void OnEndDrag() {
isDragging = false;
float posX = content.anchoredPosition.x;
int closestIndex = Mathf.RoundToInt(posX / -itemWidth);
targetX = -closestIndex * itemWidth;
}
void MoveRight(ZibuPiece piece) {
piece.transform.localPosition += new Vector3(itemWidth * pieces.Count, 0, 0);
RotateForward(piece);
}
void MoveLeft(ZibuPiece piece) {
piece.transform.localPosition -= new Vector3(itemWidth * pieces.Count, 0, 0);
RotateBackward(piece);
}
void RotateForward(ZibuPiece piece) {
centerIndex = (centerIndex + 1) % zibuSprites.Count;
ApplySprite(piece, centerIndex);
}
void RotateBackward(ZibuPiece piece) {
centerIndex = (centerIndex - 1 + zibuSprites.Count) % zibuSprites.Count;
ApplySprite(piece, centerIndex);
}
void ApplySprite(ZibuPiece piece, int index) {
piece.image.sprite = zibuSprites[index];
piece.zibuId = $"Zibu_{index}";
}
}