Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using UnityEngine.UI;
- using DG.Tweening;
- using Tools;
- namespace UI
- {
- [RequireComponent(typeof(Slider))]
- public class HealthbarAnimation : MonoBehaviour, ISliderAnimation
- {
- [SerializeField] private Image _fillImage;
- [SerializeField] private int _blinkRate = 2;
- [SerializeField] private float _speedIncrease = 0.5f;
- [SerializeField] private float _speedDecrease = 3f;
- private Slider _slider;
- private Tweener _sliderValueTweener;
- private Color _emptyColor, _fullColor;
- private float _shakeDuration = 1f, _shakeStrength = 10f;
- private void OnValidate()
- {
- _fillImage.VerifyNotNull<Image>(nameof(_fillImage));
- }
- private void Awake()
- {
- _slider = GetComponent<Slider>();
- _emptyColor = Color.red;
- _fullColor = Color.green;
- }
- private void OnEnable()
- {
- SetFillHue(_slider.value);
- }
- private float GetFillHue(float value)
- {
- return Mathf.Lerp(_emptyColor.GetHue(), _fullColor.GetHue(), value);
- }
- private void SetFillHue(float value)
- {
- var hue = GetFillHue(value);
- _fillImage.color = ColorExtension.SetHue(_emptyColor, hue);
- }
- public void SetValue(float value)
- {
- value = Mathf.Clamp(value, 0f, 1f);
- var isDecrease = value < _slider.value || value == 0;
- if (isDecrease)
- {
- DecreaseAnimation(value);
- }
- else
- {
- IncreaseAnimation(value);
- }
- }
- private void DecreaseAnimation(float value)
- {
- ShakeAnimation();
- var duration = _slider.maxValue / _speedDecrease;
- BlinkAnimation(duration);
- ChangeValueAnimation(value, duration);
- }
- private void IncreaseAnimation(float value)
- {
- var duration = _slider.maxValue / _speedIncrease;
- SetColorAnimation(value, duration);
- ChangeValueAnimation(value, duration);
- }
- private void ChangeValueAnimation(float value, float duration)
- {
- _sliderValueTweener?.Kill();
- _sliderValueTweener = _slider.DOValue(value, duration);
- }
- private void ShakeAnimation() =>
- transform.DOShakePosition(_shakeDuration, _shakeStrength);
- private void SetColorAnimation(float value, float duration)
- {
- DOTween
- .To(
- () => GetFillHue(_slider.value),
- x => _fillImage.color = ColorExtension.SetHue(_fillImage.color, x),
- GetFillHue(value),
- duration);
- }
- private void BlinkAnimation(float duration)
- {
- var loops = _blinkRate * 2;
- var oneLoopDuration = duration / loops;
- DOTween
- .To(
- () => GetFillHue(_slider.value),
- x => _fillImage.color = ColorExtension.SetHue(_fillImage.color, x),
- _emptyColor.GetHue(),
- oneLoopDuration)
- .SetLoops(loops, LoopType.Yoyo).SetEase(Ease.Linear);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement