94 lines
2.8 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class BoolView : MonoBehaviour, ISettingView
{
[Header("Layout ссылки")]
[SerializeField] private List<Graphic> ToggleGraphics;
[SerializeField] private RectTransform ToggleRect;
[Header("Настройки анимации")]
[SerializeField] private Color EnabledColor = Color.white;
[SerializeField] private Color DisabledColor = Color.gray;
[SerializeField] private Vector2 EnabledPosition;
[SerializeField] private Vector2 DisabledPosition;
[SerializeField] private float SwitchSpeed = 1000f;
[Header("Звуки")]
[SerializeField] private AudioClip EnableSound;
[SerializeField] private AudioClip DisableSound;
public bool Value { get; private set; }
public SettingDTO CachedSetting { get; private set; }
private Coroutine coroutine;
public void Initialize(SettingDTO setting)
{
this.Value = setting.BoolValue;
this.CachedSetting = setting;
DisplayImmediately();
}
public void TakeInput(int direction)
{
if (direction == 0) return;
bool newValue = direction > 0;
if (newValue == Value) return;
Value = newValue;
CachedSetting.BoolValue = newValue;
StopAllCoroutines();
StartCoroutine(Display());
}
private IEnumerator Display()
{
Vector2 targetPosition = Value ? EnabledPosition : DisabledPosition;
Vector2 startPosition = Value ? DisabledPosition : EnabledPosition;
Vector4 targetColor = Value ? EnabledColor : DisabledColor;
Color startColor = ToggleGraphics[0].color;
AudioClip clip = Value ? EnableSound : DisableSound;
SoundManager.PlayUi(clip);
while (ToggleRect.anchoredPosition != targetPosition)
{
ToggleRect.anchoredPosition = Vector2.MoveTowards(ToggleRect.anchoredPosition, targetPosition, Time.deltaTime * SwitchSpeed);
//цвет
float t = Vector2.Distance(ToggleRect.anchoredPosition, startPosition) / Vector2.Distance(startPosition, targetPosition);
Color color = ToggleGraphics[0].color;
color = Vector4.Lerp(startColor, targetColor, t);
foreach (Graphic g in ToggleGraphics)
g.color = color;
yield return null;
}
coroutine = null;
}
private void DisplayImmediately()
{
Vector2 targetPosition = Value ? EnabledPosition : DisabledPosition;
Vector4 targetColor = Value ? EnabledColor : DisabledColor;
ToggleRect.anchoredPosition = targetPosition;
foreach (Graphic g in ToggleGraphics)
g.color = targetColor;
}
private void OnDestroy()
{
StopAllCoroutines();
}
}