77 lines
2.2 KiB
C#
77 lines
2.2 KiB
C#
using System.Collections;
|
|
using UnityEngine;
|
|
using UnityEngine.UI;
|
|
|
|
public class EnemyHealthBar : MonoBehaviour
|
|
{
|
|
[SerializeField] Image FillImage;
|
|
[SerializeField] CanvasGroup canvasGroup;
|
|
[SerializeField] private float DisplayTime;
|
|
|
|
private Health healthComponent;
|
|
private float targetPercent;
|
|
private float currentVelocity;
|
|
private bool needToRefresh = false;
|
|
|
|
public void Initialize(Health healthComponent)
|
|
{
|
|
this.healthComponent = healthComponent;
|
|
healthComponent.HealthChanged += RefreshHealth;
|
|
|
|
canvasGroup.alpha = 0;
|
|
|
|
FillImage.type = Image.Type.Filled;
|
|
FillImage.fillMethod = Image.FillMethod.Horizontal;
|
|
FillImage.fillAmount = 1;
|
|
}
|
|
|
|
private void RefreshHealth(float arg)
|
|
{
|
|
targetPercent = healthComponent.Hp / healthComponent.MaxHp;
|
|
canvasGroup.alpha = 1;
|
|
needToRefresh = true;
|
|
|
|
if (Mathf.Approximately(targetPercent, 0)) StartCoroutine(FadeOutAndDestroy(2, 4));
|
|
}
|
|
|
|
private void Update()
|
|
{
|
|
Vector3 directionToCamera = (CamerasManager.CamerasPivot.position - transform.position).normalized;
|
|
transform.forward = -directionToCamera;
|
|
|
|
if (needToRefresh)
|
|
{
|
|
float percent = Mathf.SmoothDamp(FillImage.fillAmount, targetPercent, ref currentVelocity, DisplayTime);
|
|
FillImage.fillAmount = percent;
|
|
needToRefresh = !Mathf.Approximately(percent, targetPercent);
|
|
}
|
|
}
|
|
private void OnDisable() => healthComponent.HealthChanged -= RefreshHealth;
|
|
private void OnDestroy() => healthComponent.HealthChanged -= RefreshHealth;
|
|
|
|
public IEnumerator FadeOutAndDestroy(float waitTime, float fadeDuration)
|
|
{
|
|
if (canvasGroup == null)
|
|
{
|
|
Destroy(gameObject);
|
|
yield break;
|
|
}
|
|
|
|
yield return new WaitForSeconds(waitTime);
|
|
|
|
float elapsed = 0;
|
|
float startAlpha = canvasGroup.alpha;
|
|
|
|
while (elapsed < fadeDuration)
|
|
{
|
|
elapsed += Time.deltaTime;
|
|
float t = elapsed / fadeDuration;
|
|
canvasGroup.alpha = Mathf.Lerp(startAlpha, 0, t);
|
|
yield return null;
|
|
}
|
|
|
|
canvasGroup.alpha = 0;
|
|
Destroy(gameObject);
|
|
}
|
|
}
|