| | 1 | | using System; |
| | 2 | | using System.Collections; |
| | 3 | | using UnityEngine; |
| | 4 | | using UnityEngine.UI; |
| | 5 | |
|
| | 6 | | public class CursorController : MonoBehaviour |
| | 7 | | { |
| | 8 | | private const float ALPHA_INTERPOLATION_DURATION = 0.1f; |
| | 9 | |
|
| 0 | 10 | | public static CursorController i { get; private set; } |
| | 11 | | public Image cursorImage; |
| | 12 | | public Sprite normalCursor; |
| | 13 | | public Sprite hoverCursor; |
| | 14 | | public CanvasGroup canvasGroup; |
| | 15 | |
|
| | 16 | | private Coroutine alphaRoutine; |
| | 17 | |
|
| 1204 | 18 | | void Awake() { i = this; } |
| | 19 | |
|
| | 20 | | public void Show() |
| | 21 | | { |
| 79 | 22 | | if (cursorImage == null) return; |
| 23 | 23 | | if (cursorImage.gameObject.activeSelf) return; |
| | 24 | |
|
| 3 | 25 | | cursorImage.gameObject.SetActive(true); |
| | 26 | |
|
| 3 | 27 | | if (gameObject.activeSelf) |
| | 28 | | { |
| 0 | 29 | | if (alphaRoutine != null) StopCoroutine(alphaRoutine); |
| 0 | 30 | | alphaRoutine = StartCoroutine(SetAlpha(0f, 1f, ALPHA_INTERPOLATION_DURATION)); |
| | 31 | | } |
| 3 | 32 | | } |
| | 33 | |
|
| | 34 | | public void Hide() |
| | 35 | | { |
| 830 | 36 | | if (cursorImage == null) return; |
| 574 | 37 | | if (!cursorImage.gameObject.activeSelf) return; |
| | 38 | |
|
| 574 | 39 | | if (gameObject.activeSelf) |
| | 40 | | { |
| 569 | 41 | | if (alphaRoutine != null) StopCoroutine(alphaRoutine); |
| 569 | 42 | | alphaRoutine = StartCoroutine(SetAlpha(1f, 0f, ALPHA_INTERPOLATION_DURATION, |
| 139 | 43 | | () => cursorImage.gameObject.SetActive(false))); |
| 569 | 44 | | } |
| | 45 | | else |
| 5 | 46 | | cursorImage.gameObject.SetActive(false); |
| 5 | 47 | | } |
| | 48 | |
|
| | 49 | | public void SetNormalCursor() |
| | 50 | | { |
| 10 | 51 | | cursorImage.sprite = normalCursor; |
| 10 | 52 | | cursorImage.SetNativeSize(); |
| 10 | 53 | | } |
| | 54 | |
|
| | 55 | | public void SetHoverCursor() |
| | 56 | | { |
| 5 | 57 | | cursorImage.sprite = hoverCursor; |
| 5 | 58 | | cursorImage.SetNativeSize(); |
| 5 | 59 | | } |
| | 60 | |
|
| | 61 | | private IEnumerator SetAlpha(float from, float to, float duration, Action callback = null) |
| | 62 | | { |
| 569 | 63 | | var time = 0f; |
| | 64 | |
|
| 2861 | 65 | | while (time < duration) |
| | 66 | | { |
| 2722 | 67 | | time += Time.deltaTime; |
| 2722 | 68 | | canvasGroup.alpha = Mathf.Lerp(from, to, time / duration); |
| 2722 | 69 | | yield return null; |
| | 70 | | } |
| | 71 | |
|
| 139 | 72 | | canvasGroup.alpha = to; |
| 139 | 73 | | callback?.Invoke(); |
| 139 | 74 | | } |
| | 75 | | } |