LightningFieldScript.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. //
  2. // Procedural Lightning for Unity
  3. // (c) 2015 Digital Ruby, LLC
  4. // Source code may be used for personal or commercial projects.
  5. // Source code may NOT be redistributed or sold.
  6. //
  7. using UnityEngine;
  8. using System.Collections;
  9. namespace DigitalRuby.ThunderAndLightning
  10. {
  11. /// <summary>
  12. /// Lightning field script, creates lightning in a cube
  13. /// </summary>
  14. public class LightningFieldScript : LightningBoltPrefabScriptBase
  15. {
  16. /// <summary>The minimum length for a field segment</summary>
  17. [Header("Lightning Field Properties")]
  18. [Tooltip("The minimum length for a field segment")]
  19. public float MinimumLength = 0.01f;
  20. private float minimumLengthSquared;
  21. /// <summary>The bounds to put the field in.</summary>
  22. [Tooltip("The bounds to put the field in.")]
  23. public Bounds FieldBounds;
  24. /// <summary>Optional light for the lightning field to emit</summary>
  25. [Tooltip("Optional light for the lightning field to emit")]
  26. public Light Light;
  27. private Vector3 RandomPointInBounds()
  28. {
  29. float x = UnityEngine.Random.Range(FieldBounds.min.x, FieldBounds.max.x);
  30. float y = UnityEngine.Random.Range(FieldBounds.min.y, FieldBounds.max.y);
  31. float z = UnityEngine.Random.Range(FieldBounds.min.z, FieldBounds.max.z);
  32. return new Vector3(x, y, z);
  33. }
  34. /// <summary>
  35. /// Start
  36. /// </summary>
  37. protected override void Start()
  38. {
  39. base.Start();
  40. if (Light != null)
  41. {
  42. Light.enabled = false;
  43. }
  44. }
  45. /// <summary>
  46. /// Update
  47. /// </summary>
  48. protected override void Update()
  49. {
  50. base.Update();
  51. if (Time.timeScale <= 0.0f)
  52. {
  53. return;
  54. }
  55. else if (Light != null)
  56. {
  57. Light.transform.position = FieldBounds.center;
  58. Light.intensity = UnityEngine.Random.Range(2.8f, 3.2f);
  59. }
  60. }
  61. /// <summary>
  62. /// Create a lightning bolt
  63. /// </summary>
  64. /// <param name="parameters">Parameters</param>
  65. public override void CreateLightningBolt(LightningBoltParameters parameters)
  66. {
  67. minimumLengthSquared = MinimumLength * MinimumLength;
  68. for (int i = 0; i < 16; i++)
  69. {
  70. // get two random points in the bounds
  71. parameters.Start = RandomPointInBounds();
  72. parameters.End = RandomPointInBounds();
  73. if ((parameters.End - parameters.Start).sqrMagnitude >= minimumLengthSquared)
  74. {
  75. break;
  76. }
  77. }
  78. if (Light != null)
  79. {
  80. Light.enabled = true;
  81. }
  82. base.CreateLightningBolt(parameters);
  83. }
  84. }
  85. }