miepzerino
2023-12-23 eab47305629d96d19626e10b649ba4247d1f55f5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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<RectTransform>();
        textMeshPro = GetComponent<TextMeshProUGUI>();
        startingPosition = textTransform.position;
        // add random starting position for text
        randomStartingPointX = (float)new System.Random().NextDouble() - 0.5f;
        randomStartingPointY = (float)new System.Random().NextDouble() * 15f;
        textTransform.position = new Vector3(textTransform.position.x, textTransform.position.y + randomStartingPointY, textTransform.position.y);
    }
 
    private void Update()
    {
        timeElapsed += 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 * Time.deltaTime), textTransform.position.z + (moveSpeed.z * Time.deltaTime));
 
    }
}