using System.Collections; using Entity; using SepCore.UI; using UnityEngine; using UnityEngine.Serialization; using UnityEngine.UI; using UnityGameFramework.Runtime; namespace StarForce { public class HPBarItem : MonoBehaviour { private const float AnimationSeconds = 0.3f; private const float KeepSeconds = 0.4f; private const float FadeOutSeconds = 0.3f; [FormerlySerializedAs("m_HPBar")] [SerializeField] private Slider _hPBar = null; private Canvas _parentCanvas = null; private RectTransform _cachedTransform = null; private CanvasGroup _cachedCanvasGroup = null; private EntityBase _owner = null; private int m_OwnerId = 0; public EntityBase Owner => _owner; public void Init(EntityBase owner, Canvas parentCanvas, float fromHPRatio, float toHPRatio) { if (owner == null) { Log.Error("Owner is invalid."); return; } _parentCanvas = parentCanvas; gameObject.SetActive(true); StopAllCoroutines(); _cachedCanvasGroup.alpha = 1f; if (_owner != owner || m_OwnerId != owner.Id) { _hPBar.value = fromHPRatio; _owner = owner; m_OwnerId = owner.Id; } Refresh(); StartCoroutine(HPBarCo(toHPRatio, AnimationSeconds, KeepSeconds, FadeOutSeconds)); } public bool Refresh() { if (_cachedCanvasGroup.alpha <= 0f) { return false; } if (_owner != null && Owner.Available && Owner.Id == m_OwnerId) { Vector3 worldPosition = _owner.CachedTransform.position + Vector3.forward; Vector3 screenPosition = GameEntry.Scene.MainCamera.WorldToScreenPoint(worldPosition); Vector2 position; if (RectTransformUtility.ScreenPointToLocalPointInRectangle((RectTransform)_parentCanvas.transform, screenPosition, _parentCanvas.worldCamera, out position)) { _cachedTransform.localPosition = position; } } return true; } public void Reset() { StopAllCoroutines(); _cachedCanvasGroup.alpha = 1f; _hPBar.value = 1f; _owner = null; gameObject.SetActive(false); } private void Awake() { _cachedTransform = GetComponent(); if (_cachedTransform == null) { Log.Error("RectTransform is invalid."); return; } _cachedCanvasGroup = GetComponent(); if (_cachedCanvasGroup == null) { Log.Error("CanvasGroup is invalid."); return; } } private IEnumerator HPBarCo(float value, float animationDuration, float keepDuration, float fadeOutDuration) { yield return _hPBar.SmoothValue(value, animationDuration); yield return new WaitForSeconds(keepDuration); yield return _cachedCanvasGroup.FadeToAlpha(0f, fadeOutDuration); } } }