using System;
|
using TMPro;
|
using UnityEngine;
|
|
public class WorldSpaceText : MonoBehaviour
|
{
|
public Vector3 moveSpeed = new Vector3(0.25f, 0.75f, 0);
|
public float oscillationsPerSecond = 1.0f;
|
public float timeToFade = 1f;
|
public float startToFade = 1f;
|
private float timeElapsed = 0f;
|
public bool randomStartingPoint = false;
|
private float randomStartingPointX = 0f;
|
private float randomStartingPointY = 0f;
|
private Vector3 startingPosition;
|
|
private TextMeshProUGUI textMeshPro;
|
|
private void Awake()
|
{
|
textMeshPro = GetComponent<TextMeshProUGUI>();
|
startingPosition = transform.position;
|
|
// Add random starting position for text
|
if (randomStartingPoint)
|
{
|
randomStartingPointX = UnityEngine.Random.value - 0.5f;
|
randomStartingPointY = UnityEngine.Random.value * 0.15f;
|
}
|
transform.position = new Vector3(transform.position.x, transform.position.y + randomStartingPointY, transform.position.z);
|
|
// Ensure text faces camera
|
transform.rotation = Camera.main.transform.rotation;
|
}
|
|
private void Update()
|
{
|
timeElapsed += Time.deltaTime;
|
float deltaTime = Time.deltaTime;
|
|
// Always face camera
|
transform.rotation = Camera.main.transform.rotation;
|
|
if (timeElapsed >= startToFade)
|
{
|
// Start fading when "startToFade" time is reached
|
textMeshPro.alpha = (1 - ((timeElapsed - startToFade) / timeToFade));
|
if (timeElapsed >= (startToFade + timeToFade))
|
{
|
Destroy(gameObject);
|
}
|
}
|
|
// Calculate oscillation phase
|
float phase = ((randomStartingPointX + timeElapsed) * oscillationsPerSecond * (2f * Mathf.PI));
|
|
// Set new position of object (using world space values)
|
transform.position = new Vector3(
|
startingPosition.x + (Mathf.Sin(phase) * moveSpeed.x),
|
transform.position.y + (moveSpeed.y * deltaTime),
|
transform.position.z + (moveSpeed.z * deltaTime));
|
}
|
}
|