Skip to content

Commit

Permalink
animation logic for tooltip
Browse files Browse the repository at this point in the history
  • Loading branch information
bozmir committed Sep 20, 2024
1 parent 06a45cc commit 8009072
Showing 1 changed file with 46 additions and 2 deletions.
48 changes: 46 additions & 2 deletions Assets/Scripts/UI/Components/TooltipDialog.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using DG.Tweening;
using System;
using System.Collections;
using TMPro;
Expand All @@ -14,7 +15,11 @@ public class TooltipDialog : MonoBehaviour

private TextMeshProUGUI tooltiptext;
private RectTransform rectTransform;
private RectTransform lastTarget;
private RectTransform currentTarget;
private ContentSizeFitter contentSizeFitter;
private Sequence animationSequence;
private const float animationDuration = 0.25f;
private Vector3[] worldCorners = new Vector3[4];

#region Singleton
Expand Down Expand Up @@ -75,6 +80,9 @@ public void AlignOnElement(RectTransform element)
{
if (!element) return;

lastTarget = currentTarget;
currentTarget = element;

var elementCenter = GetRectTransformBounds(element).center;
var elementMax = GetRectTransformBounds(element).max;

Expand All @@ -96,6 +104,11 @@ public void ShowMessage(string message = "Tooltip", RectTransform hoverTarget =
tooltiptext.text = message;

StartCoroutine(FitContent());

StartAnimation(1f, () =>
{
});
}

private IEnumerator FitContent()
Expand All @@ -106,8 +119,11 @@ private IEnumerator FitContent()
}

public void Hide()
{
gameObject.SetActive(false);
{
StartAnimation(0f, ()=> {
if(lastTarget == currentTarget || currentTarget == null)
gameObject.SetActive(false);
});
}

private Bounds GetRectTransformBounds(RectTransform transform)
Expand All @@ -121,5 +137,33 @@ private Bounds GetRectTransformBounds(RectTransform transform)

return bounds;
}


private void StartAnimation(float targetScale, Action onFinish = null)
{
// If the animation is playing, quickly complete it and then start a new one
if (animationSequence != null && animationSequence.IsPlaying())
{
animationSequence.Complete(true);
}
animationSequence = CreateAnimationSequence(targetScale, onFinish);
animationSequence.Play();
}

private Sequence CreateAnimationSequence(float scale, Action onFinish = null)
{
Sequence sequence = DOTween.Sequence(rectTransform);
sequence.SetEase(scale > 0 ? Ease.OutBounce : Ease.InBack);
sequence.Join(rectTransform.DOScale(scale, scale > 0 ? animationDuration : 0.5f * animationDuration));

// Ensure animation sequence is nulled after completing to clean up
sequence.OnComplete(() =>
{
onFinish?.Invoke();
animationSequence = null;
});

return sequence;
}
}
}

0 comments on commit 8009072

Please sign in to comment.