2026-01-12 09:36:17 +03:00

114 lines
3.4 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
public class BoolView : MonoBehaviour, IView
{
[SerializeField] private List<Graphic> ToggleGraphics;
[SerializeField] private RectTransform ToggleRect;
[SerializeField] private Color EnabledColor = new Vector4(1, 1, 1, 1);
[SerializeField] private Color DisabledColor = new Vector4(0.5f, 0.5f, 0.5f, 1);
[SerializeField] private Vector2 EnabledPosition;
[SerializeField] private Vector2 DisabledPosition;
[SerializeField] private AudioClip EnableSound;
[SerializeField] private AudioClip DisableSound;
[SerializeField] private float switchDuration = 0.2f;
Vector2 toggleVelocity = Vector2.zero;
bool value;
public UnityEvent OnChangeReady { get; }
private Coroutine coroutine;
public void ChangeValue(string settingId)
{
bool newValue = SettingsManager.GetBool(settingId, false);
if (newValue == value) return;
value = newValue;
if (coroutine == null)
coroutine = StartCoroutine(Display(value, switchDuration, sounded: true));
}
public void Initialize(string settingId)
{
Setting setting = SettingsManager.Container.TryGetSetting(settingId);
if (setting.Type != SettingType.Bool)
{
Debug.LogError("Настройка не того типа (bool)");
return;
}
this.value = setting.BoolValue;
Vector4 targetColor = value ? EnabledColor : DisabledColor;
foreach (Graphic g in ToggleGraphics)
{
g.color = targetColor;
}
coroutine = null;
if (coroutine == null)
coroutine = StartCoroutine(Display(this.value, 0.001f, sounded: false));
}
IEnumerator Display(bool value, float duration, bool sounded)
{
Vector2 targetPosition = value ? EnabledPosition : DisabledPosition;
Vector2 startPosition = value ? DisabledPosition : EnabledPosition;
Vector4 targetColor = value ? EnabledColor : DisabledColor;
Color startColor = ToggleGraphics[0].color;
if (sounded)
{
AudioClip clip = value ? EnableSound : DisableSound;
SoundManager.instance.playClip(clip);
}
while (ToggleRect.anchoredPosition != targetPosition)
{
ToggleRect.anchoredPosition =Vector2.SmoothDamp(current: ToggleRect.anchoredPosition,
target: targetPosition,
currentVelocity: ref toggleVelocity,
smoothTime: switchDuration);
//цвет
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 = targetColor;
}
//приблизительность флоата...
if (Vector2.Distance(ToggleRect.anchoredPosition, targetPosition) < 0.001f)
{
ToggleRect.anchoredPosition = targetPosition; break;
}
yield return null;
}
coroutine = null;
}
}