ExampleTimeColor.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. using UnityEngine;
  2. namespace Chronos.Example
  3. {
  4. // Utility script to change the color of a game object based
  5. // on the time scale of its timeline.
  6. public class ExampleTimeColor : MonoBehaviour
  7. {
  8. // The state colors
  9. private Color rewind = Color.magenta;
  10. private Color pause = Color.red;
  11. private Color slow = Color.yellow;
  12. private Color play = Color.green;
  13. private Color accelerate = Color.blue;
  14. // The time scales at which to apply colors
  15. private float slowTimeScale = 0.5f;
  16. private float rewindTimeScale = -1f;
  17. private float accelerateTimeScale = 2f;
  18. private Timeline time;
  19. private new Renderer renderer;
  20. private new ParticleSystem particleSystem;
  21. private void Awake()
  22. {
  23. time = GetComponentInParent<Timeline>();
  24. renderer = GetComponent<Renderer>();
  25. particleSystem = GetComponent<ParticleSystem>();
  26. }
  27. private void Update()
  28. {
  29. Color color = Color.white;
  30. // Get the timeline in the ancestors
  31. if (time != null)
  32. {
  33. float timeScale = time.timeScale;
  34. // Color lerping magic :)
  35. if (timeScale < 0)
  36. {
  37. color = Color.Lerp(pause, rewind, Mathf.Max(rewindTimeScale, timeScale) / rewindTimeScale);
  38. }
  39. else if (timeScale < slowTimeScale)
  40. {
  41. color = Color.Lerp(pause, slow, timeScale / slowTimeScale);
  42. }
  43. else if (timeScale < 1)
  44. {
  45. color = Color.Lerp(slow, play, (timeScale - slowTimeScale) / (1 - slowTimeScale));
  46. }
  47. else
  48. {
  49. color = Color.Lerp(play, accelerate, (timeScale - 1) / (accelerateTimeScale - 1));
  50. }
  51. }
  52. // Apply the color to the renderer (if any)
  53. if (renderer != null)
  54. {
  55. foreach (Material material in GetComponent<Renderer>().materials)
  56. {
  57. material.color = color;
  58. }
  59. }
  60. // Apply the color to the particle system (if any)
  61. if (particleSystem != null)
  62. {
  63. var particleSystemMain = particleSystem.main;
  64. particleSystemMain.startColor = color;
  65. var colorModule = particleSystem.colorOverLifetime;
  66. colorModule.color = new ParticleSystem.MinMaxGradient(color);
  67. }
  68. }
  69. }
  70. }