75 lines
1.7 KiB
C#
Raw Normal View History

2022-02-24 23:13:31 -08:00
using System.Linq;
using UnityEngine;
2022-02-18 05:33:48 -08:00
using UnityEngine.Rendering;
namespace QSB.PlayerBodySetup.Remote;
public class QSBDitheringAnimator : MonoBehaviour
2022-02-18 05:33:48 -08:00
{
2022-02-24 23:13:31 -08:00
public bool FullyVisible => !enabled && OWMath.ApproxEquals(_visibleFraction, 1);
public bool FullyInvisible => !enabled && OWMath.ApproxEquals(_visibleFraction, 0);
private float _visibleTarget = 1;
private float _visibleFraction = 1;
private float _fadeRate;
private (OWRenderer Renderer, bool UpdateShadows)[] _renderers;
2022-02-18 05:33:48 -08:00
private void Awake()
{
2022-02-24 23:13:31 -08:00
_renderers = GetComponentsInChildren<Renderer>(true)
.Select(x => (x.gameObject.GetAddComponent<OWRenderer>(), x.shadowCastingMode != ShadowCastingMode.Off))
.ToArray();
enabled = false;
}
2022-02-18 05:33:48 -08:00
2022-02-24 23:13:31 -08:00
public void SetVisible(bool visible, float seconds = 0)
{
2022-02-24 23:13:31 -08:00
var visibleTarget = visible ? 1 : 0;
if (OWMath.ApproxEquals(visibleTarget, _visibleTarget))
2022-02-18 05:33:48 -08:00
{
2022-02-24 23:13:31 -08:00
return;
}
2022-02-24 23:13:31 -08:00
_visibleTarget = visibleTarget;
if (seconds != 0)
{
2022-02-24 23:13:31 -08:00
_fadeRate = 1 / seconds;
enabled = true;
2022-02-18 05:33:48 -08:00
}
2022-02-24 23:13:31 -08:00
else
{
_visibleFraction = _visibleTarget;
UpdateRenderers();
}
}
2022-02-18 05:33:48 -08:00
private void Update()
{
2022-02-24 23:13:31 -08:00
_visibleFraction = Mathf.MoveTowards(_visibleFraction, _visibleTarget, _fadeRate * Time.deltaTime);
if (OWMath.ApproxEquals(_visibleFraction, _visibleTarget))
2022-02-18 05:33:48 -08:00
{
2022-02-24 23:13:31 -08:00
_visibleFraction = _visibleTarget;
enabled = false;
2022-02-18 05:33:48 -08:00
}
2022-02-24 23:13:31 -08:00
UpdateRenderers();
}
2022-02-24 23:13:31 -08:00
private void UpdateRenderers()
{
2022-02-24 23:13:31 -08:00
foreach (var (renderer, updateShadows) in _renderers)
2022-02-18 05:33:48 -08:00
{
2022-02-24 23:13:31 -08:00
if (renderer == null)
2022-02-18 05:33:48 -08:00
{
2022-02-24 23:13:31 -08:00
continue;
2022-02-18 05:33:48 -08:00
}
2022-02-24 23:13:31 -08:00
renderer.SetDitherFade(1 - _visibleFraction);
if (updateShadows)
2022-02-18 05:33:48 -08:00
{
2022-02-24 23:13:31 -08:00
renderer._renderer.shadowCastingMode = FullyVisible ? ShadowCastingMode.On : ShadowCastingMode.Off;
2022-02-18 05:33:48 -08:00
}
}
}
2022-02-24 23:13:31 -08:00
}