HealthBarUi.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. using Sirenix.OdinInspector;
  6. namespace KairoEngine.CharacterSystem
  7. {
  8. public class HealthBarUi : MonoBehaviour
  9. {
  10. [BoxGroup("State"), ReadOnly]
  11. public Transform target;
  12. [BoxGroup("State"), ReadOnly]
  13. public float valueForeground = 50f;
  14. [BoxGroup("State"), ReadOnly]
  15. public float valueBackground = 150f;
  16. [FoldoutGroup("Configurations")]
  17. public RectTransform rectTransform;
  18. [FoldoutGroup("Configurations")]
  19. public RectTransform foregroundObj;
  20. [FoldoutGroup("Configurations")]
  21. public RectTransform backgroundObj;
  22. [FoldoutGroup("Configurations")]
  23. public Image foregroundImg;
  24. [FoldoutGroup("Configurations")]
  25. public Image backgroundImg;
  26. [FoldoutGroup("Configurations")]
  27. public float hideTime = 2f;
  28. private float hideTimeCounter = 0f;
  29. public void Setup(DamageController damageController)
  30. {
  31. hideTimeCounter = 0f;
  32. target = damageController.transform;
  33. valueForeground = damageController.HP;
  34. valueBackground = damageController.maxHP;
  35. }
  36. public void Update()
  37. {
  38. if (target != null && rectTransform != null)
  39. {
  40. Vector3 headPos = new Vector3(target.position.x, target.position.y + 2.2f, target.position.z);
  41. Vector3 screenPos = Camera.main.WorldToScreenPoint(headPos);
  42. rectTransform.position = screenPos;
  43. SetPercentage();
  44. }
  45. hideTimeCounter += Time.deltaTime;
  46. if(hideTimeCounter >= hideTime)
  47. {
  48. hideTimeCounter = 0f;
  49. gameObject.SetActive(false);
  50. }
  51. }
  52. void SetPercentage()
  53. {
  54. float width = backgroundObj.rect.width;
  55. float newWidth = (width * valueForeground) / valueBackground;
  56. if (newWidth > width) newWidth = width;
  57. if (newWidth < 0) newWidth = 0;
  58. foregroundObj.sizeDelta = new Vector2(newWidth, backgroundObj.rect.height);
  59. }
  60. }
  61. }