ThunderAndLightningScript.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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. /// Thunder and lightning script for random lightning bolts
  13. /// </summary>
  14. public class ThunderAndLightningScript : MonoBehaviour
  15. {
  16. private class LightningBoltHandler
  17. {
  18. public float VolumeMultiplier { get; set; }
  19. private ThunderAndLightningScript script;
  20. private readonly System.Random random = new System.Random();
  21. public LightningBoltHandler(ThunderAndLightningScript script)
  22. {
  23. this.script = script;
  24. CalculateNextLightningTime();
  25. }
  26. private void UpdateLighting()
  27. {
  28. if (script.lightningInProgress)
  29. {
  30. return;
  31. }
  32. if (script.ModifySkyboxExposure)
  33. {
  34. script.skyboxExposureStorm = 0.35f;
  35. if (script.skyboxMaterial != null && script.skyboxMaterial.HasProperty("_Exposure"))
  36. {
  37. script.skyboxMaterial.SetFloat("_Exposure", script.skyboxExposureStorm);
  38. }
  39. }
  40. CheckForLightning();
  41. }
  42. private void CalculateNextLightningTime()
  43. {
  44. script.nextLightningTime = DigitalRuby.ThunderAndLightning.LightningBoltScript.TimeSinceStart + script.LightningIntervalTimeRange.Random(random);
  45. script.lightningInProgress = false;
  46. if (script.ModifySkyboxExposure && script.skyboxMaterial.HasProperty("_Exposure"))
  47. {
  48. script.skyboxMaterial.SetFloat("_Exposure", script.skyboxExposureStorm);
  49. }
  50. }
  51. public IEnumerator ProcessLightning(Vector3? _start, Vector3? _end, bool intense, bool visible)
  52. {
  53. float sleepTime;
  54. AudioClip[] sounds;
  55. float intensity;
  56. script.lightningInProgress = true;
  57. if (intense)
  58. {
  59. float percent = UnityEngine.Random.Range(0.0f, 1.0f);
  60. intensity = Mathf.Lerp(2.0f, 8.0f, percent);
  61. sleepTime = 5.0f / intensity;
  62. sounds = script.ThunderSoundsIntense;
  63. }
  64. else
  65. {
  66. float percent = UnityEngine.Random.Range(0.0f, 1.0f);
  67. intensity = Mathf.Lerp(0.0f, 2.0f, percent);
  68. sleepTime = 30.0f / intensity;
  69. sounds = script.ThunderSoundsNormal;
  70. }
  71. if (script.skyboxMaterial != null && script.ModifySkyboxExposure)
  72. {
  73. script.skyboxMaterial.SetFloat("_Exposure", Mathf.Max(intensity * 0.5f, script.skyboxExposureStorm));
  74. }
  75. // perform the strike
  76. Strike(_start, _end, intense, intensity, script.Camera, visible ? script.Camera : null);
  77. // calculate the next lightning strike
  78. CalculateNextLightningTime();
  79. // thunder will play depending on intensity of lightning
  80. bool playThunder = (intensity >= 1.0f);
  81. //Debug.Log("Lightning intensity: " + intensity.ToString("0.00") + ", thunder delay: " +
  82. // (playThunder ? sleepTime.ToString("0.00") : "No Thunder"));
  83. if (playThunder && sounds != null && sounds.Length > 0)
  84. {
  85. // wait for a bit then play a thunder sound
  86. yield return WaitForSecondsLightning.WaitForSecondsLightningPooled(sleepTime);
  87. AudioClip clip = null;
  88. do
  89. {
  90. // pick a random thunder sound that wasn't the same as the last sound, unless there is only one sound, then we have no choice
  91. clip = sounds[UnityEngine.Random.Range(0, sounds.Length - 1)];
  92. }
  93. while (sounds.Length > 1 && clip == script.lastThunderSound);
  94. // set the last sound and play it
  95. script.lastThunderSound = clip;
  96. script.audioSourceThunder.PlayOneShot(clip, intensity * 0.5f * VolumeMultiplier);
  97. }
  98. }
  99. private void Strike(Vector3? _start, Vector3? _end, bool intense, float intensity, Camera camera, Camera visibleInCamera)
  100. {
  101. // find a point around the camera that is not too close
  102. const float minDistance = 500.0f;
  103. float minValue = (intense ? -1000.0f : -5000.0f);
  104. float maxValue = (intense ? 1000 : 5000.0f);
  105. float closestValue = (intense ? 500.0f : 2500.0f);
  106. float x, y, z;
  107. Vector3 start, end;
  108. bool areaBounded = (_start is null && _end is null && script.AreaOveride != null);
  109. if (areaBounded)
  110. {
  111. var bounds = script.AreaOveride.bounds;
  112. x = UnityEngine.Random.Range(bounds.min.x, bounds.max.x);
  113. y = UnityEngine.Random.Range(bounds.min.y, bounds.max.y);
  114. z = UnityEngine.Random.Range(bounds.min.z, bounds.max.z);
  115. start = new Vector3(x, y, z);
  116. }
  117. else
  118. {
  119. x = (UnityEngine.Random.Range(0, 2) == 0 ? UnityEngine.Random.Range(minValue, -closestValue) : UnityEngine.Random.Range(closestValue, maxValue));
  120. y = script.LightningYStart;
  121. z = (UnityEngine.Random.Range(0, 2) == 0 ? UnityEngine.Random.Range(minValue, -closestValue) : UnityEngine.Random.Range(closestValue, maxValue));
  122. start = script.Camera.transform.position;
  123. start.x += x;
  124. start.y = y;
  125. start.z += z;
  126. if (visibleInCamera != null)
  127. {
  128. // try and make sure the strike is visible in the camera
  129. Quaternion q = visibleInCamera.transform.rotation;
  130. visibleInCamera.transform.rotation = Quaternion.Euler(0.0f, q.eulerAngles.y, 0.0f);
  131. float screenX = UnityEngine.Random.Range(visibleInCamera.pixelWidth * 0.1f, visibleInCamera.pixelWidth * 0.9f);
  132. float ScreenZ = UnityEngine.Random.Range(visibleInCamera.nearClipPlane + closestValue + closestValue, maxValue);
  133. Vector3 point = visibleInCamera.ScreenToWorldPoint(new Vector3(screenX, 0.0f, ScreenZ));
  134. start = point;
  135. start.y = y;
  136. visibleInCamera.transform.rotation = q;
  137. }
  138. }
  139. end = start;
  140. x = UnityEngine.Random.Range(-100, 100.0f);
  141. // 1 in 4 chance not to strike the ground
  142. y = (UnityEngine.Random.Range(0, 4) == 0 ? UnityEngine.Random.Range(-1, 600.0f) : -1.0f);
  143. z += UnityEngine.Random.Range(-100.0f, 100.0f);
  144. end.x += x;
  145. end.y = y;
  146. end.z += z;
  147. // make sure the bolt points away from the camera
  148. end.x += (closestValue * camera.transform.forward.x);
  149. end.z += (closestValue * camera.transform.forward.z);
  150. while ((start - end).magnitude < minDistance)
  151. {
  152. end.x += (closestValue * camera.transform.forward.x);
  153. end.z += (closestValue * camera.transform.forward.z);
  154. }
  155. start = (_start ?? start);
  156. end = (_end ?? end);
  157. // see if the bolt hit anything on it's way to the ground - if so, change the end point
  158. RaycastHit hit;
  159. if (Physics.Raycast(start, (start - end).normalized, out hit, float.MaxValue))
  160. {
  161. end = hit.point;
  162. }
  163. int generations = script.LightningBoltScript.Generations;
  164. RangeOfFloats trunkWidth = script.LightningBoltScript.TrunkWidthRange;
  165. if (UnityEngine.Random.value < script.CloudLightningChance)
  166. {
  167. // cloud only lightning
  168. script.LightningBoltScript.TrunkWidthRange = new RangeOfFloats();
  169. script.LightningBoltScript.Generations = 1;
  170. }
  171. script.LightningBoltScript.LightParameters.LightIntensity = intensity * 0.5f;
  172. script.LightningBoltScript.Trigger(start, end);
  173. script.LightningBoltScript.TrunkWidthRange = trunkWidth;
  174. script.LightningBoltScript.Generations = generations;
  175. }
  176. private void CheckForLightning()
  177. {
  178. // time for another strike?
  179. if (Time.timeSinceLevelLoad >= script.nextLightningTime)
  180. {
  181. bool intense = UnityEngine.Random.value < script.LightningIntenseProbability;
  182. script.StartCoroutine(ProcessLightning(null, null, intense, script.LightningAlwaysVisible));
  183. }
  184. }
  185. public void Update()
  186. {
  187. UpdateLighting();
  188. }
  189. }
  190. /// <summary>Lightning bolt script - optional, leave null if you don't want lightning bolts</summary>
  191. [Tooltip("Lightning bolt script - optional, leave null if you don't want lightning bolts")]
  192. public LightningBoltPrefabScript LightningBoltScript;
  193. /// <summary>Camera where the lightning should be centered over. Defaults to main camera.</summary>
  194. [Tooltip("Camera where the lightning should be centered over. Defaults to main camera.")]
  195. public Camera Camera;
  196. /// <summary>Random interval between strikes.</summary>
  197. [SingleLine("Random interval between strikes.")]
  198. public RangeOfFloats LightningIntervalTimeRange = new RangeOfFloats { Minimum = 10.0f, Maximum = 25.0f };
  199. /// <summary>Probability (0-1) of an intense lightning bolt that hits really close. Intense lightning has increased brightness and louder thunder compared to normal lightning, and the thunder sounds plays a lot sooner.</summary>
  200. [Tooltip("Probability (0-1) of an intense lightning bolt that hits really close. Intense lightning has increased brightness and louder thunder compared to normal lightning, and the thunder sounds plays a lot sooner.")]
  201. [Range(0.0f, 1.0f)]
  202. public float LightningIntenseProbability = 0.2f;
  203. /// <summary>Sounds to play for normal thunder. One will be chosen at random for each lightning strike. Depending on intensity, some normal lightning may not play a thunder sound.</summary>
  204. [Tooltip("Sounds to play for normal thunder. One will be chosen at random for each lightning strike. Depending on intensity, some normal lightning may not play a thunder sound.")]
  205. public AudioClip[] ThunderSoundsNormal;
  206. /// <summary>Sounds to play for intense thunder. One will be chosen at random for each lightning strike.</summary>
  207. [Tooltip("Sounds to play for intense thunder. One will be chosen at random for each lightning strike.")]
  208. public AudioClip[] ThunderSoundsIntense;
  209. /// <summary>Whether lightning strikes should always try to be in the camera view</summary>
  210. [Tooltip("Whether lightning strikes should always try to be in the camera view")]
  211. public bool LightningAlwaysVisible = true;
  212. /// <summary>The chance lightning will simply be in the clouds with no visible bolt</summary>
  213. [Tooltip("The chance lightning will simply be in the clouds with no visible bolt")]
  214. [Range(0.0f, 1.0f)]
  215. public float CloudLightningChance = 0.5f;
  216. /// <summary>Whether to modify the skybox exposure when lightning is created</summary>
  217. [Tooltip("Whether to modify the skybox exposure when lightning is created")]
  218. public bool ModifySkyboxExposure = false;
  219. /// <summary>Base point light range for lightning bolts. Increases as intensity increases.</summary>
  220. [Tooltip("Base point light range for lightning bolts. Increases as intensity increases.")]
  221. [Range(1, 10000)]
  222. public float BaseLightRange = 2000.0f;
  223. /// <summary>Starting y value for the lightning strikes</summary>
  224. [Tooltip("Starting y value for the lightning strikes")]
  225. [Range(0, 100000)]
  226. public float LightningYStart = 500.0f;
  227. /// <summary>Volume multiplier</summary>
  228. [Tooltip("Volume multiplier")]
  229. [Range(0.0f, 1.0f)]
  230. public float VolumeMultiplier = 1.0f;
  231. /// <summary>Override the lightning strike area, takes all dimensions into account</summary>
  232. [Tooltip("Override the lightning strike area, takes all dimensions into account")]
  233. public BoxCollider AreaOveride;
  234. private float skyboxExposureOriginal;
  235. private float skyboxExposureStorm;
  236. private float nextLightningTime;
  237. private bool lightningInProgress;
  238. private AudioSource audioSourceThunder;
  239. private LightningBoltHandler lightningBoltHandler;
  240. private Material skyboxMaterial;
  241. private AudioClip lastThunderSound;
  242. private void Start()
  243. {
  244. EnableLightning = true;
  245. if (Camera == null)
  246. {
  247. Camera = Camera.main;
  248. }
  249. #if DEBUG
  250. if (Camera.farClipPlane < 10000.0f && !Camera.orthographic)
  251. {
  252. Debug.LogWarning("Far clip plane should be 10000+ for best lightning effects");
  253. }
  254. #endif
  255. if (RenderSettings.skybox != null)
  256. {
  257. skyboxMaterial = RenderSettings.skybox = new Material(RenderSettings.skybox);
  258. }
  259. skyboxExposureOriginal = skyboxExposureStorm = (skyboxMaterial == null || !skyboxMaterial.HasProperty("_Exposure") ? 1.0f : skyboxMaterial.GetFloat("_Exposure"));
  260. audioSourceThunder = gameObject.AddComponent<AudioSource>();
  261. lightningBoltHandler = new LightningBoltHandler(this);
  262. lightningBoltHandler.VolumeMultiplier = VolumeMultiplier;
  263. }
  264. private void Update()
  265. {
  266. if (lightningBoltHandler != null && EnableLightning)
  267. {
  268. lightningBoltHandler.VolumeMultiplier = VolumeMultiplier;
  269. lightningBoltHandler.Update();
  270. }
  271. }
  272. /// <summary>
  273. /// Summon normal lighntning at a random position
  274. /// </summary>
  275. public void CallNormalLightning()
  276. {
  277. CallNormalLightning(null, null);
  278. }
  279. /// <summary>
  280. /// Summon normal lightning
  281. /// </summary>
  282. /// <param name="start">Start position</param>
  283. /// <param name="end">End position</param>
  284. public void CallNormalLightning(Vector3? start, Vector3? end)
  285. {
  286. StartCoroutine(lightningBoltHandler.ProcessLightning(start, end, false, true));
  287. }
  288. /// <summary>
  289. /// Summon intense lightning at random location
  290. /// </summary>
  291. public void CallIntenseLightning()
  292. {
  293. CallIntenseLightning(null, null);
  294. }
  295. /// <summary>
  296. /// Summon intense lightning
  297. /// </summary>
  298. /// <param name="start">Start position</param>
  299. /// <param name="end">End position</param>
  300. public void CallIntenseLightning(Vector3? start, Vector3? end)
  301. {
  302. StartCoroutine(lightningBoltHandler.ProcessLightning(start, end, true, true));
  303. }
  304. /// <summary>
  305. /// Skybox exposure original value
  306. /// </summary>
  307. public float SkyboxExposureOriginal
  308. {
  309. get { return skyboxExposureOriginal; }
  310. }
  311. /// <summary>
  312. /// Whether to enable lightning
  313. /// </summary>
  314. public bool EnableLightning { get; set; }
  315. }
  316. }