MIF_E31230837/Assets/Script/SlideGesture.cs

123 lines
3.6 KiB
C#

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class SlideGesture : MonoBehaviour
{
[Header("Slides")]
public GameObject[] slides;
[Header("Dot Indicator (opsional)")]
public Image[] dots;
public Color dotActive = Color.white;
public Color dotInactive = new Color(1, 1, 1, 0.35f);
[Header("Swipe Setting")]
public float swipeThreshold = 50f;
private int currentIndex = 0;
private float touchStartY = 0f;
private bool isSwiping = false;
void Start()
{
ShowSlide(0);
}
void Update()
{
// Hanya proses swipe kalau panel ini aktif
if (!gameObject.activeInHierarchy) return;
// Touch
if (Input.touchCount > 0)
{
Touch t = Input.GetTouch(0);
// Abaikan kalau touch kena button
if (EventSystem.current.IsPointerOverGameObject(t.fingerId))
{
// Cek apakah yang di-touch adalah slide area, bukan button
// Kalau kena UI selain slide, biarkan
if (IsTouchOnButton(t.fingerId))
{
isSwiping = false;
return;
}
}
if (t.phase == TouchPhase.Began)
{
touchStartY = t.position.y;
isSwiping = true;
}
else if (t.phase == TouchPhase.Ended && isSwiping)
{
float diff = touchStartY - t.position.y;
ProcessSwipe(diff);
isSwiping = false;
}
}
// Mouse (Editor)
if (Input.GetMouseButtonDown(0))
{
// Abaikan kalau klik button
if (!IsPointerOnButton())
{
touchStartY = Input.mousePosition.y;
isSwiping = true;
}
}
if (Input.GetMouseButtonUp(0) && isSwiping)
{
float diff = touchStartY - Input.mousePosition.y;
ProcessSwipe(diff);
isSwiping = false;
}
}
void ProcessSwipe(float diff)
{
if (diff > swipeThreshold && currentIndex < slides.Length - 1)
ShowSlide(currentIndex + 1);
else if (diff < -swipeThreshold && currentIndex > 0)
ShowSlide(currentIndex - 1);
}
// Cek apakah pointer sedang di atas Button
bool IsPointerOnButton()
{
var results = new System.Collections.Generic.List<RaycastResult>();
var ped = new PointerEventData(EventSystem.current)
{ position = Input.mousePosition };
EventSystem.current.RaycastAll(ped, results);
foreach (var r in results)
if (r.gameObject.GetComponent<Button>() != null) return true;
return false;
}
bool IsTouchOnButton(int fingerId)
{
var results = new System.Collections.Generic.List<RaycastResult>();
var ped = new PointerEventData(EventSystem.current)
{ position = Input.GetTouch(0).position };
EventSystem.current.RaycastAll(ped, results);
foreach (var r in results)
if (r.gameObject.GetComponent<Button>() != null) return true;
return false;
}
void ShowSlide(int index)
{
currentIndex = index;
for (int i = 0; i < slides.Length; i++)
slides[i].SetActive(i == currentIndex);
if (dots != null)
for (int i = 0; i < dots.Length; i++)
dots[i].color = i == currentIndex ? dotActive : dotInactive;
}
public void ResetToFirst() => ShowSlide(0);
}