hellbound/Assets/Scripts/Game/UI/BackgroundController.cs

106 lines
2.7 KiB
C#
Raw Permalink Normal View History

2021-11-26 11:16:25 +03:00
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
public class BackgroundController : MonoBehaviour
{
[SerializeField] private Image _backgroundImage;
[SerializeField] [Range(0, 1)] private float _maxBackgroundAlpha = .787f;
[SerializeField] private AnimationCurve _showCurve;
[SerializeField] private AnimationCurve _hideCurve;
[SerializeField] private float _showTime;
[SerializeField] private float _hideTime;
private Coroutine _showHandle;
private Coroutine _hideHandle;
private bool _showInProgress;
private bool _hideInProgress;
private float _currentProgress;
public void Init()
{
SetAlpha(_backgroundImage, 0);
_backgroundImage.enabled = false;
}
public void Show()
{
if (_showInProgress)
return;
if (_hideInProgress)
{
StopCoroutine(_hideHandle);
_hideInProgress = false;
_showHandle = StartCoroutine(ShowCoroutine(1 - _currentProgress));
return;
}
_showHandle = StartCoroutine(ShowCoroutine(0));
}
public void Hide()
{
if (_hideInProgress)
return;
if (_showInProgress)
{
StopCoroutine(_showHandle);
_showInProgress = false;
_hideHandle = StartCoroutine(HideCoroutine(1 - _currentProgress));
return;
}
_hideHandle = StartCoroutine(HideCoroutine(0));
}
private IEnumerator ShowCoroutine(float start_progress)
{
_showInProgress = true;
_backgroundImage.enabled = true;
yield return Toggle(start_progress, _showCurve, _showTime, 0, _maxBackgroundAlpha);
_showInProgress = false;
}
private IEnumerator HideCoroutine(float start_progress)
{
_hideInProgress = true;
yield return Toggle(start_progress, _hideCurve, _hideTime, _maxBackgroundAlpha, 0);
_backgroundImage.enabled = false;
_hideInProgress = false;
}
private IEnumerator Toggle(float start_progress, AnimationCurve curve, float toggle_time, float start_value, float end_value)
{
_currentProgress = start_progress;
var time = _currentProgress * toggle_time;
while (time < toggle_time)
{
_currentProgress = time / toggle_time;
var alpha = Mathf.LerpUnclamped(start_value, end_value, curve.Evaluate(_currentProgress));
SetAlpha(_backgroundImage, alpha);
time += Time.deltaTime;
yield return null;
}
SetAlpha(_backgroundImage, end_value);
}
private void SetAlpha(Image img, float alpha)
{
Color imgColor = img.color;
imgColor.a = alpha;
img.color = imgColor;
}
}