Edwarddv

LightClicker

Mar 17th, 2019
206
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.28 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class LightFlicker : MonoBehaviour
  5. {
  6.  
  7.     private Transform thisTransform;
  8.     private Light thisLight;
  9.     public float baseLightIntensity = 1f;
  10.     private float previousIntensity;
  11.     private float nextIntensity;
  12.  
  13.     public float flickerRange = 0.2f;
  14.     public float movementFlickerAmount = 0.05f;
  15.     public float flickerRate = 0.1f;
  16.     private float flickerClock;
  17.     private Vector3 startPosition;
  18.     public bool smoothMotion = false;
  19.     private Vector3 lastPosition;
  20.     private Vector3 nextPosition;
  21.     // Use this for initialization
  22.     void Start ()
  23.     {
  24.         if (thisLight == null) thisLight = GetComponent<Light>();
  25.         baseLightIntensity = thisLight.intensity;
  26.         previousIntensity = baseLightIntensity;
  27.         nextIntensity = baseLightIntensity + Random.Range(-flickerRange, flickerRange);
  28.         thisTransform = transform;
  29.         startPosition = thisTransform.localPosition;
  30.         lastPosition = startPosition;
  31.         nextPosition = startPosition + Random.insideUnitSphere * movementFlickerAmount;
  32.     }
  33.    
  34.     // Update is called once per frame
  35.     void Update ()
  36.     {
  37.         if (flickerRate == 0f)
  38.             return;
  39.  
  40.         if (flickerClock < flickerRate)
  41.         {
  42.             flickerClock += Time.deltaTime;
  43.         }
  44.  
  45.         if (smoothMotion)
  46.         {
  47.             flickerClock = Mathf.Clamp(flickerClock, 0f, flickerRate);
  48.             thisTransform.localPosition = Vector3.Lerp(lastPosition, nextPosition, flickerClock / flickerRate);
  49.             thisLight.intensity = Mathf.Lerp(previousIntensity,nextIntensity, flickerClock / flickerRate);
  50.  
  51.         }
  52.  
  53.         if (flickerClock >= flickerRate)
  54.         {
  55.             if (flickerRange > 0f)
  56.             {
  57.                 thisLight.intensity = nextIntensity;
  58.  
  59.                 previousIntensity = nextIntensity;
  60.                 nextIntensity = baseLightIntensity + Random.Range(-flickerRange, flickerRange);
  61.             }
  62.  
  63.             if (movementFlickerAmount > 0f)
  64.             {
  65.                 thisTransform.localPosition = nextPosition;
  66.  
  67.                 lastPosition = nextPosition;
  68.                 nextPosition = startPosition + Random.insideUnitSphere * movementFlickerAmount;
  69.  
  70.             }
  71.  
  72.             flickerClock = 0f;
  73.         }
  74.  
  75.  
  76.  
  77.     }
  78. }
Advertisement
Add Comment
Please, Sign In to add comment