Last active
July 30, 2020 05:09
-
-
Save joliveriwp/6001966d874102758228085ffad5096c to your computer and use it in GitHub Desktop.
Unity - Simple flickering light source using Light2D.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Generic; | |
using UnityEngine; | |
using UnityEngine.Experimental.Rendering.Universal; | |
public class TorchLight : MonoBehaviour | |
{ | |
[Range(1, 100)] | |
public int flickerSpeed = 50; | |
[SerializeField] | |
private float minIntensity = 0.2f; | |
[SerializeField] | |
private float maxIntensity = 1.0f; | |
[SerializeField] | |
private float minOuterRadius = 0.5f; | |
[SerializeField] | |
private float maxOuterRadius = 1.0f; | |
private float randIntensity; | |
private float randOuterRadius; | |
private float lastFlicker; | |
public new Light2D light; | |
Queue<float> flickerQueue; | |
private void Reset() | |
{ | |
flickerQueue.Clear(); | |
lastFlicker = 0; | |
} | |
private void Start() | |
{ | |
flickerQueue = new Queue<float>(flickerSpeed); | |
if (light == null) | |
{ | |
light = GetComponent<Light2D>(); | |
} | |
} | |
private void FixedUpdate() | |
{ | |
if (light == null) | |
{ | |
return; | |
} | |
while (flickerQueue.Count >= flickerSpeed) | |
{ | |
lastFlicker -= flickerQueue.Dequeue(); | |
} | |
randIntensity = Random.Range(minIntensity, maxIntensity); | |
flickerQueue.Enqueue(randIntensity); | |
lastFlicker += randIntensity; | |
randOuterRadius = Random.Range(minOuterRadius, maxOuterRadius); | |
flickerQueue.Enqueue(randOuterRadius); | |
lastFlicker += randOuterRadius; | |
light.intensity = lastFlicker / flickerQueue.Count; | |
light.pointLightOuterRadius = lastFlicker / flickerQueue.Count; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment