Files
2026-06-09 14:40:32 +02:00

80 lines
2.5 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;
[Header("Glitch Object")]
public GameObject glitchObject;
void OnEnable()
{
_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)
{
if (flickerSpeed > 0f)
{
float t = Mathf.PerlinNoise(Time.time * flickerSpeed + _randomOffset, 0f);
ApplyFlicker(t);
}
else
{
if (targetLight) targetLight.intensity = 0f;
}
if (Random.value < glitchChance * Time.deltaTime)
yield return StartCoroutine(GlitchBurst());
yield return null;
}
}
private IEnumerator GlitchBurst()
{
float elapsed = 0f;
float duration = Random.Range(glitchMinDuration, glitchMaxDuration);
if (glitchObject) glitchObject.SetActive(true);
while (elapsed < duration)
{
ApplyFlicker(Random.value);
elapsed += Time.deltaTime;
yield return null;
}
if (glitchObject) glitchObject.SetActive(false);
if (targetLight) targetLight.intensity = 0f;
}
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);
}
}
}