using System; using System.Collections; using System.Collections.Generic; using TMPro; using UnityEngine; public class HealthText : MonoBehaviour { // x = oscillation amount (0 = no oscillation), y = upwards speed public Vector3 moveSpeed = new Vector3(25f, 75, 0); // oscillation speed public float oscillationsPerSecond = 1.0f; // x of seconds it takes to fade away public float timeToFade = 1f; // start fading after x seconds public float startToFade = 1f; private float timeElapsed = 0f; private float randomStartingPointX; private float randomStartingPointY; private Vector3 startingPosition; RectTransform textTransform; TextMeshProUGUI textMeshPro; private void Awake() { textTransform = GetComponent(); textMeshPro = GetComponent(); startingPosition = textTransform.position; // add random starting position for text randomStartingPointX = UnityEngine.Random.value - 0.5f; randomStartingPointY = UnityEngine.Random.value * 15f; textTransform.position = new Vector3(textTransform.position.x, textTransform.position.y + randomStartingPointY, textTransform.position.y); } private void Update() { timeElapsed += Time.deltaTime; float deltaTime = Time.deltaTime; if (timeElapsed >= startToFade) { // start fading when "startToFade" time is reached textMeshPro.alpha = (1 - ((timeElapsed - startToFade) / timeToFade)); if (timeElapsed >= (startToFade + timeToFade)) { // destroy object when end of live is reached Destroy(gameObject); } } // calc oscillation phase float phase = ((randomStartingPointX + timeElapsed) * oscillationsPerSecond * (2f * Mathf.PI)); // set new position of object textTransform.position = new Vector3(startingPosition.x + (Mathf.Sin(phase) * moveSpeed.x), textTransform.position.y + (moveSpeed.y * deltaTime), textTransform.position.z + (moveSpeed.z * deltaTime)); } }