You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
HighGroundRoyaleNetcode/Assets/Scripts/Gameplay/UI/FloatingScore.cs

70 lines
2.4 KiB
C#

using UnityEngine;
using TMPro;
using UnityEngine.UI;
using System.Collections;
namespace Unity.BossRoom.Gameplay.UI
{
public class FloatingScore : MonoBehaviour
{
[SerializeField] private TextMeshProUGUI scoreChangeText; // The text component
[SerializeField] private Image backgroundImage; // The background image
[SerializeField] private float animationDuration = 1.5f; // How long the animation lasts
[SerializeField] private Vector3 floatOffset = new Vector3(0, 2f, 0); // How far upward to move
private CanvasGroup canvasGroup; // Used for fading
private void Awake()
{
canvasGroup = gameObject.AddComponent<CanvasGroup>(); // Adds a CanvasGroup for fading
}
/// <summary>
/// Initializes the floating score effect.
/// </summary>
/// <param name="change">The amount by which the score changed.</param>
public void Initialize(int change)
{
// Set the text to display the score change, adding a '+' for positive changes.
if (change >= 0)
{
scoreChangeText.text = $"+{change}";
backgroundImage.color = new Color(0.66f, 1f, 0.38f, 1f); // Green for increases
}
else
{
scoreChangeText.text = $"{change}";
backgroundImage.color = new Color(1f, 0.4f, 0.38f, 1f); // Red for decreases
}
StartCoroutine(Animate());
}
/// <summary>
/// Animates the floating score effect.
/// </summary>
private IEnumerator Animate()
{
float elapsedTime = 0f;
Vector3 startPosition = transform.position;
Vector3 endPosition = startPosition + floatOffset;
while (elapsedTime < animationDuration)
{
float t = elapsedTime / animationDuration;
transform.position = Vector3.Lerp(startPosition, endPosition, t);
canvasGroup.alpha = Mathf.Lerp(1f, 0f, t);
elapsedTime += Time.deltaTime;
yield return null;
}
// Ensure final position and alpha values
transform.position = endPosition;
canvasGroup.alpha = 0f;
Destroy(gameObject); // Destroy the effect once the animation is complete
}
}
}