DynamicFogManager.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. using UnityEngine;
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. namespace DynamicFogAndMist
  6. {
  7. [ExecuteInEditMode]
  8. [HelpURL ("http://kronnect.com/taptapgo")]
  9. public class DynamicFogManager : MonoBehaviour
  10. {
  11. [Range (0, 1)]
  12. public float
  13. alpha = 1f;
  14. [Range (0, 1)]
  15. public float
  16. noiseStrength = 0.5f;
  17. [Range (0, 0.999f)]
  18. public float
  19. distance = 0.2f;
  20. [Range (0, 2f)]
  21. public float
  22. distanceFallOff = 1f;
  23. [Range (0, 500)]
  24. public float
  25. height = 1f;
  26. [Range (0, 1)]
  27. public float
  28. heightFallOff = 1f;
  29. public float
  30. baselineHeight = 0;
  31. public Color color = new Color (0.89f, 0.89f, 0.89f, 1);
  32. public GameObject sun;
  33. Light sunLight;
  34. Vector3 sunDirection = Vector3.zero;
  35. Color sunColor = Color.white;
  36. float sunIntensity = 1f;
  37. // Creates a private material used to the effect
  38. void OnEnable ()
  39. {
  40. UpdateMaterialProperties ();
  41. }
  42. void Reset ()
  43. {
  44. UpdateMaterialProperties ();
  45. }
  46. // Check possible alpha transition
  47. void Update ()
  48. {
  49. // Updates sun illumination
  50. if (sun != null) {
  51. bool needFogColorUpdate = false;
  52. if (sun.transform.forward != sunDirection) {
  53. needFogColorUpdate = true;
  54. }
  55. if (sunLight != null) {
  56. if (sunLight.color != sunColor || sunLight.intensity != sunIntensity) {
  57. needFogColorUpdate = true;
  58. }
  59. }
  60. if (needFogColorUpdate)
  61. UpdateFogColor ();
  62. }
  63. UpdateFogData();
  64. }
  65. public void UpdateMaterialProperties ()
  66. {
  67. UpdateFogData();
  68. UpdateFogColor ();
  69. }
  70. void UpdateFogData() {
  71. Vector4 data = new Vector4 (height + 0.001f, baselineHeight, Camera.main.farClipPlane * distance, heightFallOff);
  72. Shader.SetGlobalVector ("_FogData", data);
  73. Shader.SetGlobalFloat ("_FogData2", distanceFallOff * data.z + 0.0001f);
  74. }
  75. void UpdateFogColor ()
  76. {
  77. if (sun != null) {
  78. if (sunLight == null)
  79. sunLight = sun.GetComponent<Light> ();
  80. if (sunLight != null && sunLight.transform != sun.transform) {
  81. sunLight = sun.GetComponent<Light> ();
  82. }
  83. sunDirection = sun.transform.forward;
  84. if (sunLight != null) {
  85. sunColor = sunLight.color;
  86. sunIntensity = sunLight.intensity;
  87. }
  88. }
  89. float fogIntensity = sunIntensity * Mathf.Clamp01 (1.0f - sunDirection.y);
  90. Color fogColor = color * sunColor * fogIntensity;
  91. fogColor.a = alpha;
  92. Shader.SetGlobalColor ("_FogColor", fogColor);
  93. }
  94. }
  95. }