60 lines
1.6 KiB
C#
60 lines
1.6 KiB
C#
using UnityEngine;
|
|
using UnityEngine.UI;
|
|
|
|
public class HealthBar : MonoBehaviour
|
|
{
|
|
[SerializeField] private GameObject container;
|
|
[SerializeField] private Image healthBarFill;
|
|
[SerializeField] private CanvasGroup canvasGroup;
|
|
|
|
float lastHitTime;
|
|
private float previousHealth = 1;
|
|
private float normalizedHealth = 1;
|
|
private const float MAX_TIME_ALLOWED = 3.0f;
|
|
|
|
public bool ShowBar = true;
|
|
|
|
private void Start()
|
|
{
|
|
container.SetActive(false);
|
|
}
|
|
|
|
public void SetHealth(float normalizedHealth)
|
|
{
|
|
healthBarFill.color = Color.Lerp(Color.red, Color.green, normalizedHealth);
|
|
healthBarFill.fillAmount = normalizedHealth;
|
|
this.normalizedHealth = normalizedHealth;
|
|
}
|
|
|
|
public GameObject GetContainer() => container;
|
|
public CanvasGroup GetCanvasGroup() => canvasGroup;
|
|
|
|
|
|
//rotate the healthbar so its always looking at the camera.
|
|
private void Update()
|
|
{
|
|
if (Player.Instance != null && container.activeInHierarchy)
|
|
{
|
|
transform.rotation = Quaternion.LookRotation(Player.Instance.GetPlayerFirstPersonCameraPosition() - transform.position);
|
|
}
|
|
|
|
if (ShowBar)
|
|
{
|
|
//if the player has hit the enemy within the last 3 seconds. if they've not, disable it
|
|
if (GotHit())
|
|
{
|
|
lastHitTime = Time.time;
|
|
previousHealth = normalizedHealth;
|
|
}
|
|
|
|
container.SetActive(Time.time - lastHitTime <= MAX_TIME_ALLOWED);
|
|
}
|
|
|
|
}
|
|
|
|
private bool GotHit()
|
|
{
|
|
return previousHealth != normalizedHealth;
|
|
}
|
|
}
|