LightningBoltScript.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. //
  2. // Lightning Bolt for Unity
  3. // (c) 2016 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.Generic;
  9. namespace DigitalRuby.LightningBolt
  10. {
  11. /// <summary>
  12. /// Types of animations for lightning bolts
  13. /// </summary>
  14. public enum LightningBoltAnimationMode
  15. {
  16. /// <summary>
  17. /// No animation
  18. /// </summary>
  19. None,
  20. /// <summary>
  21. /// Pick a random frame
  22. /// </summary>
  23. Random,
  24. /// <summary>
  25. /// Loop through each frame and restart at the beginning
  26. /// </summary>
  27. Loop,
  28. /// <summary>
  29. /// Loop through each frame then go backwards to the beginning then forward, etc.
  30. /// </summary>
  31. PingPong
  32. }
  33. /// <summary>
  34. /// Allows creation of simple lightning bolts
  35. /// </summary>
  36. [RequireComponent(typeof(LineRenderer))]
  37. public class LightningBoltScript : MonoBehaviour
  38. {
  39. [Tooltip("The game object where the lightning will emit from. If null, StartPosition is used.")]
  40. public GameObject StartObject;
  41. [Tooltip("The start position where the lightning will emit from. This is in world space if StartObject is null, otherwise this is offset from StartObject position.")]
  42. public Vector3 StartPosition;
  43. [Tooltip("The game object where the lightning will end at. If null, EndPosition is used.")]
  44. public GameObject EndObject;
  45. [Tooltip("The end position where the lightning will end at. This is in world space if EndObject is null, otherwise this is offset from EndObject position.")]
  46. public Vector3 EndPosition;
  47. [Range(0, 8)]
  48. [Tooltip("How manu generations? Higher numbers create more line segments.")]
  49. public int Generations = 6;
  50. [Range(0.01f, 1.0f)]
  51. [Tooltip("How long each bolt should last before creating a new bolt. In ManualMode, the bolt will simply disappear after this amount of seconds.")]
  52. public float Duration = 0.05f;
  53. private float timer;
  54. [Range(0.0f, 1.0f)]
  55. [Tooltip("How chaotic should the lightning be? (0-1)")]
  56. public float ChaosFactor = 0.15f;
  57. [Tooltip("In manual mode, the trigger method must be called to create a bolt")]
  58. public bool ManualMode;
  59. [Range(1, 64)]
  60. [Tooltip("The number of rows in the texture. Used for animation.")]
  61. public int Rows = 1;
  62. [Range(1, 64)]
  63. [Tooltip("The number of columns in the texture. Used for animation.")]
  64. public int Columns = 1;
  65. [Tooltip("The animation mode for the lightning")]
  66. public LightningBoltAnimationMode AnimationMode = LightningBoltAnimationMode.PingPong;
  67. /// <summary>
  68. /// Assign your own random if you want to have the same lightning appearance
  69. /// </summary>
  70. [HideInInspector]
  71. [System.NonSerialized]
  72. public System.Random RandomGenerator = new System.Random();
  73. private LineRenderer lineRenderer;
  74. private List<KeyValuePair<Vector3, Vector3>> segments = new List<KeyValuePair<Vector3, Vector3>>();
  75. private int startIndex;
  76. private Vector2 size;
  77. private Vector2[] offsets;
  78. private int animationOffsetIndex;
  79. private int animationPingPongDirection = 1;
  80. private bool orthographic;
  81. private void GetPerpendicularVector(ref Vector3 directionNormalized, out Vector3 side)
  82. {
  83. if (directionNormalized == Vector3.zero)
  84. {
  85. side = Vector3.right;
  86. }
  87. else
  88. {
  89. // use cross product to find any perpendicular vector around directionNormalized:
  90. // 0 = x * px + y * py + z * pz
  91. // => pz = -(x * px + y * py) / z
  92. // for computational stability use the component farthest from 0 to divide by
  93. float x = directionNormalized.x;
  94. float y = directionNormalized.y;
  95. float z = directionNormalized.z;
  96. float px, py, pz;
  97. float ax = Mathf.Abs(x), ay = Mathf.Abs(y), az = Mathf.Abs(z);
  98. if (ax >= ay && ay >= az)
  99. {
  100. // x is the max, so we can pick (py, pz) arbitrarily at (1, 1):
  101. py = 1.0f;
  102. pz = 1.0f;
  103. px = -(y * py + z * pz) / x;
  104. }
  105. else if (ay >= az)
  106. {
  107. // y is the max, so we can pick (px, pz) arbitrarily at (1, 1):
  108. px = 1.0f;
  109. pz = 1.0f;
  110. py = -(x * px + z * pz) / y;
  111. }
  112. else
  113. {
  114. // z is the max, so we can pick (px, py) arbitrarily at (1, 1):
  115. px = 1.0f;
  116. py = 1.0f;
  117. pz = -(x * px + y * py) / z;
  118. }
  119. side = new Vector3(px, py, pz).normalized;
  120. }
  121. }
  122. private void GenerateLightningBolt(Vector3 start, Vector3 end, int generation, int totalGenerations, float offsetAmount)
  123. {
  124. if (generation < 0 || generation > 8)
  125. {
  126. return;
  127. }
  128. else if (orthographic)
  129. {
  130. start.z = end.z = Mathf.Min(start.z, end.z);
  131. }
  132. segments.Add(new KeyValuePair<Vector3, Vector3>(start, end));
  133. if (generation == 0)
  134. {
  135. return;
  136. }
  137. Vector3 randomVector;
  138. if (offsetAmount <= 0.0f)
  139. {
  140. offsetAmount = (end - start).magnitude * ChaosFactor;
  141. }
  142. while (generation-- > 0)
  143. {
  144. int previousStartIndex = startIndex;
  145. startIndex = segments.Count;
  146. for (int i = previousStartIndex; i < startIndex; i++)
  147. {
  148. start = segments[i].Key;
  149. end = segments[i].Value;
  150. // determine a new direction for the split
  151. Vector3 midPoint = (start + end) * 0.5f;
  152. // adjust the mid point to be the new location
  153. RandomVector(ref start, ref end, offsetAmount, out randomVector);
  154. midPoint += randomVector;
  155. // add two new segments
  156. segments.Add(new KeyValuePair<Vector3, Vector3>(start, midPoint));
  157. segments.Add(new KeyValuePair<Vector3, Vector3>(midPoint, end));
  158. }
  159. // halve the distance the lightning can deviate for each generation down
  160. offsetAmount *= 0.5f;
  161. }
  162. }
  163. public void RandomVector(ref Vector3 start, ref Vector3 end, float offsetAmount, out Vector3 result)
  164. {
  165. if (orthographic)
  166. {
  167. Vector3 directionNormalized = (end - start).normalized;
  168. Vector3 side = new Vector3(-directionNormalized.y, directionNormalized.x, directionNormalized.z);
  169. float distance = ((float)RandomGenerator.NextDouble() * offsetAmount * 2.0f) - offsetAmount;
  170. result = side * distance;
  171. }
  172. else
  173. {
  174. Vector3 directionNormalized = (end - start).normalized;
  175. Vector3 side;
  176. GetPerpendicularVector(ref directionNormalized, out side);
  177. // generate random distance
  178. float distance = (((float)RandomGenerator.NextDouble() + 0.1f) * offsetAmount);
  179. // get random rotation angle to rotate around the current direction
  180. float rotationAngle = ((float)RandomGenerator.NextDouble() * 360.0f);
  181. // rotate around the direction and then offset by the perpendicular vector
  182. result = Quaternion.AngleAxis(rotationAngle, directionNormalized) * side * distance;
  183. }
  184. }
  185. private void SelectOffsetFromAnimationMode()
  186. {
  187. int index;
  188. if (AnimationMode == LightningBoltAnimationMode.None)
  189. {
  190. lineRenderer.material.mainTextureOffset = offsets[0];
  191. return;
  192. }
  193. else if (AnimationMode == LightningBoltAnimationMode.PingPong)
  194. {
  195. index = animationOffsetIndex;
  196. animationOffsetIndex += animationPingPongDirection;
  197. if (animationOffsetIndex >= offsets.Length)
  198. {
  199. animationOffsetIndex = offsets.Length - 2;
  200. animationPingPongDirection = -1;
  201. }
  202. else if (animationOffsetIndex < 0)
  203. {
  204. animationOffsetIndex = 1;
  205. animationPingPongDirection = 1;
  206. }
  207. }
  208. else if (AnimationMode == LightningBoltAnimationMode.Loop)
  209. {
  210. index = animationOffsetIndex++;
  211. if (animationOffsetIndex >= offsets.Length)
  212. {
  213. animationOffsetIndex = 0;
  214. }
  215. }
  216. else
  217. {
  218. index = RandomGenerator.Next(0, offsets.Length);
  219. }
  220. if (index >= 0 && index < offsets.Length)
  221. {
  222. lineRenderer.material.mainTextureOffset = offsets[index];
  223. }
  224. else
  225. {
  226. lineRenderer.material.mainTextureOffset = offsets[0];
  227. }
  228. }
  229. private void UpdateLineRenderer()
  230. {
  231. int segmentCount = (segments.Count - startIndex) + 1;
  232. lineRenderer.positionCount = segmentCount;
  233. if (segmentCount < 1)
  234. {
  235. return;
  236. }
  237. int index = 0;
  238. lineRenderer.SetPosition(index++, segments[startIndex].Key);
  239. for (int i = startIndex; i < segments.Count; i++)
  240. {
  241. lineRenderer.SetPosition(index++, segments[i].Value);
  242. }
  243. segments.Clear();
  244. SelectOffsetFromAnimationMode();
  245. }
  246. private void Start()
  247. {
  248. orthographic = (Camera.main != null && Camera.main.orthographic);
  249. lineRenderer = GetComponent<LineRenderer>();
  250. lineRenderer.positionCount = 0;
  251. UpdateFromMaterialChange();
  252. }
  253. private void Update()
  254. {
  255. orthographic = (Camera.main != null && Camera.main.orthographic);
  256. if (timer <= 0.0f)
  257. {
  258. if (ManualMode)
  259. {
  260. timer = Duration;
  261. lineRenderer.positionCount = 0;
  262. }
  263. else
  264. {
  265. Trigger();
  266. }
  267. }
  268. timer -= Time.deltaTime;
  269. }
  270. /// <summary>
  271. /// Trigger a lightning bolt. Use this if ManualMode is true.
  272. /// </summary>
  273. public void Trigger()
  274. {
  275. Vector3 start, end;
  276. timer = Duration + Mathf.Min(0.0f, timer);
  277. if (StartObject == null)
  278. {
  279. start = StartPosition;
  280. }
  281. else
  282. {
  283. start = StartObject.transform.position + StartPosition;
  284. }
  285. if (EndObject == null)
  286. {
  287. end = EndPosition;
  288. }
  289. else
  290. {
  291. end = EndObject.transform.position + EndPosition;
  292. }
  293. startIndex = 0;
  294. GenerateLightningBolt(start, end, Generations, Generations, 0.0f);
  295. UpdateLineRenderer();
  296. }
  297. /// <summary>
  298. /// Call this method if you change the material on the line renderer
  299. /// </summary>
  300. public void UpdateFromMaterialChange()
  301. {
  302. size = new Vector2(1.0f / (float)Columns, 1.0f / (float)Rows);
  303. lineRenderer.material.mainTextureScale = size;
  304. offsets = new Vector2[Rows * Columns];
  305. for (int y = 0; y < Rows; y++)
  306. {
  307. for (int x = 0; x < Columns; x++)
  308. {
  309. offsets[x + (y * Columns)] = new Vector2((float)x / Columns, (float)y / Rows);
  310. }
  311. }
  312. }
  313. }
  314. }