Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using DG.Tweening;
- using UnityEngine;
- using UnityEngine.UI;
- namespace JasonStorey
- {
- public class Bar : MonoBehaviour
- {
- [Header("Dependencies")]
- [SerializeField]
- Image _fill;
- [SerializeField]
- Image _buffer;
- [SerializeField]
- Image _flash;
- [Header("Settings")]
- [SerializeField]
- int _max = 100;
- [SerializeField]
- int _value = 20;
- public void TakeDamage(int amount)
- {
- float currentPercent = (float)_value / _max;
- _value = Mathf.Max(0,_value - amount);
- float targetPercent = (float)_value / _max;
- Fill = targetPercent;
- _buffer.fillAmount = currentPercent;
- Buffer = targetPercent;
- Shake();
- }
- #region Plumbing
- void Shake()
- {
- _shaker.Restart();
- _shaker.Play();
- }
- [ContextMenu("Replenish")]
- public void Replenish()
- {
- _value = _max;
- DOVirtual
- .Float(_fill.fillAmount, 1, 1f,x=>_fill.fillAmount = x)
- .SetEase(Ease.OutSine).OnComplete(Flash);
- }
- float Fill
- {
- set => _fill.fillAmount = value;
- }
- float Buffer
- {
- set
- {
- DOVirtual
- .Float(_buffer.fillAmount, value, 0.3f,x=>_buffer.fillAmount = x)
- .SetEase(Ease.InSine);
- }
- }
- public Color FlashColor;
- [ContextMenu("Flash")]
- void Flash()
- {
- _flash.color = FlashColor;
- _flash.DOColor(_fill.color,1f).SetEase(Ease.OutSine).OnComplete(()=>_flash.color = Color.clear);
- Shake();
- }
- void OnValidate()
- {
- Max = _max;
- Value = _value;
- }
- public int Value
- {
- get => _value;
- set => _value = Mathf.Clamp(value, 0, _max);
- }
- public int Max
- {
- get => _max;
- set => _max = Mathf.Max(1, value);
- }
- public float Percent
- {
- get => _fill.fillAmount;
- set
- {
- var val = Mathf.Lerp(0, Max, value);
- _value = (int) val;
- _fill.fillAmount = _buffer.fillAmount = val / Max;
- }
- }
- void Start()
- {
- _shaker = transform.DOPunchPosition(Vector3.right * 6, 0.3f, 20).SetAutoKill(false);
- }
- void OnDestroy()
- {
- _shaker.Kill();
- }
- Tweener _shaker;
- #endregion
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement