Advertisement
Guest User

Flicker Script

a guest
Feb 3rd, 2018
9,302
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.86 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class FlickeringLight : MonoBehaviour {
  6.  
  7.     public enum WaveForm { sin, tri, sqr, saw, inv, noise };
  8.     public WaveForm waveform = WaveForm.sin;
  9.  
  10.     public float delay = 0; // delay time
  11.     public float baseStart = 0.0f; //start
  12.     public float amplitude = 1.0f; //amplitude of the wave
  13.     public float phase = 0.0f; // start point inside on wave cycle
  14.     public float frequency = 0.5f; // cycle frequency per second
  15.  
  16.     //keep a copy of the orignal color
  17.     private Color originalColor;
  18.     private Light light;
  19.  
  20.     private int x = 0;
  21.     //Store the original color
  22.     void Start () {
  23.         light = GetComponent<Light>();
  24.         originalColor = light.color;
  25.     }
  26.    
  27.     // Update is called once per frame
  28.     void FixedUpdate () {
  29.         x += 1;
  30.  
  31.         if (x >= delay)
  32.         {
  33.             light.color = originalColor * (EvalWave());
  34.             x = 0;
  35.         }
  36.     }
  37.  
  38.     float EvalWave()
  39.     {
  40.         float x = (Time.time + phase) * frequency;
  41.         float y;
  42.         x = x - Mathf.Floor(x); // normalized value (0..1)
  43.  
  44.         if( waveform == WaveForm.sin)
  45.         {
  46.             y = Mathf.Sin(x * 2 * Mathf.PI);
  47.         }
  48.         else if (waveform == WaveForm.tri)
  49.         {
  50.  
  51.             if ( x < 0.5f)
  52.             {
  53.                 y = 1.0f;
  54.             }
  55.             else
  56.             {
  57.                 y = -1.0f;
  58.             }
  59.         }
  60.         else if (waveform == WaveForm.saw)
  61.         {
  62.             y = x;
  63.         }
  64.         else if (waveform == WaveForm.inv)
  65.         {
  66.             y = 1.0f - x;
  67.         }
  68.         else if (waveform == WaveForm.noise)
  69.         {
  70.             y = 1f - (Random.value * 2);
  71.         }
  72.         else
  73.         {
  74.             y = 1.0f;
  75.         }
  76.  
  77.         return (y * amplitude) + baseStart;
  78.     }
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement