63 lines
1.6 KiB
C#
63 lines
1.6 KiB
C#
using UnityEngine;
|
|
using UnityEngine.EventSystems;
|
|
using UnityEngine.UI;
|
|
using System.Collections;
|
|
|
|
public class HoverSlideButton : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
|
|
{
|
|
public RectTransform buttonTransform;
|
|
|
|
public Vector2 offPosition = Vector2.zero;
|
|
public Vector2 onPosition = new Vector2(30f, 0f); // e.g., slide 30px to the right
|
|
|
|
public float slideDuration = 0.2f;
|
|
|
|
private Coroutine slideCoroutine;
|
|
private bool isOn = false;
|
|
|
|
private void Reset()
|
|
{
|
|
buttonTransform = GetComponent<RectTransform>();
|
|
}
|
|
|
|
public void OnPointerEnter(PointerEventData eventData)
|
|
{
|
|
SlideToPosition(onPosition);
|
|
}
|
|
|
|
public void OnPointerExit(PointerEventData eventData)
|
|
{
|
|
if (!isOn) SlideToPosition(offPosition);
|
|
|
|
}
|
|
|
|
public void SetOnState(bool on)
|
|
{
|
|
isOn = on;
|
|
SlideToPosition(on ? onPosition : offPosition);
|
|
}
|
|
|
|
private void SlideToPosition(Vector2 target)
|
|
{
|
|
if (slideCoroutine != null)
|
|
StopCoroutine(slideCoroutine);
|
|
|
|
slideCoroutine = StartCoroutine(SmoothSlide(target));
|
|
}
|
|
|
|
private IEnumerator SmoothSlide(Vector2 target)
|
|
{
|
|
Vector2 startPos = buttonTransform.anchoredPosition;
|
|
float timeElapsed = 0f;
|
|
|
|
while (timeElapsed < slideDuration)
|
|
{
|
|
buttonTransform.anchoredPosition = Vector2.Lerp(startPos, target, timeElapsed / slideDuration);
|
|
timeElapsed += Time.deltaTime;
|
|
yield return null;
|
|
}
|
|
|
|
buttonTransform.anchoredPosition = target;
|
|
}
|
|
}
|