66 lines
2.0 KiB
C#
66 lines
2.0 KiB
C#
using System.Collections;
|
|
using UnityEngine;
|
|
|
|
namespace Unheimlich.VFX
|
|
{
|
|
public class LightFlicker : MonoBehaviour
|
|
{
|
|
public Light targetLight;
|
|
|
|
[Tooltip("Flicker oscillates around this value. Driven each frame by ScarecrowFire.")]
|
|
public float baseIntensity = 0f;
|
|
|
|
[Range(0f, 1f)] public float flickerRange = 0.3f;
|
|
public float flickerSpeed = 5f;
|
|
|
|
[Range(0f, 1f)] public float glitchChance = 0.15f;
|
|
public float glitchMinDuration = 0.02f;
|
|
public float glitchMaxDuration = 0.12f;
|
|
|
|
private float _randomOffset;
|
|
|
|
void Start()
|
|
{
|
|
_randomOffset = Random.Range(0f, 1000f);
|
|
StartCoroutine(FlickerRoutine());
|
|
}
|
|
|
|
/// <summary>Called each frame by ScarecrowFire to update the base the flicker oscillates around.</summary>
|
|
public void SetBaseIntensity(float value) => baseIntensity = value;
|
|
|
|
private IEnumerator FlickerRoutine()
|
|
{
|
|
while (true)
|
|
{
|
|
float t = Mathf.PerlinNoise(Time.time * flickerSpeed + _randomOffset, 0f);
|
|
ApplyFlicker(t);
|
|
|
|
if (Random.value < glitchChance)
|
|
yield return StartCoroutine(GlitchBurst());
|
|
|
|
yield return null;
|
|
}
|
|
}
|
|
|
|
private IEnumerator GlitchBurst()
|
|
{
|
|
float elapsed = 0f;
|
|
float duration = Random.Range(glitchMinDuration, glitchMaxDuration);
|
|
|
|
while (elapsed < duration)
|
|
{
|
|
ApplyFlicker(Random.value);
|
|
elapsed += Time.deltaTime;
|
|
yield return null;
|
|
}
|
|
}
|
|
|
|
private void ApplyFlicker(float t)
|
|
{
|
|
if (targetLight == null) return;
|
|
float offset = Mathf.Lerp(-baseIntensity * flickerRange,
|
|
baseIntensity * flickerRange, t);
|
|
targetLight.intensity = Mathf.Max(0f, baseIntensity + offset);
|
|
}
|
|
}
|
|
} |