Newer
Older
DungeonShooting / DungeonShooting_Godot / src / game / ui / roomUI / HealthBar.cs
  1. using System;
  2. using Godot;
  3.  
  4. namespace UI.RoomUI;
  5.  
  6. public class HealthBar
  7. {
  8. private RoomUI.UiNode_HealthBar _healthBar;
  9. // 当前血量
  10. private int _hp;
  11. // 最大血量
  12. private int _maxHp;
  13. // 当前护盾值
  14. private int _shield;
  15. // 最大护盾值
  16. private int _maxShield;
  17.  
  18. private EventFactory _eventFactory;
  19. public HealthBar(RoomUI.UiNode_HealthBar healthBar)
  20. {
  21. _healthBar = healthBar;
  22. }
  23.  
  24. public void OnShow()
  25. {
  26. _eventFactory = EventManager.CreateEventFactory();
  27. _eventFactory.AddEventListener(EventEnum.OnPlayerHpChange, OnPlayerHpChange);
  28. _eventFactory.AddEventListener(EventEnum.OnPlayerMaxHpChange, OnPlayerMaxHpChange);
  29. _eventFactory.AddEventListener(EventEnum.OnPlayerShieldChange, OnPlayerShieldChange);
  30. _eventFactory.AddEventListener(EventEnum.OnPlayerMaxShieldChange, OnPlayerMaxShieldChange);
  31. }
  32.  
  33. public void OnHide()
  34. {
  35. _eventFactory.RemoveAllEventListener();
  36. }
  37.  
  38. /// <summary>
  39. /// 设置最大血量
  40. /// </summary>
  41. public void SetMaxHp(int maxHp)
  42. {
  43. _maxHp = Mathf.Max(maxHp, 0);
  44. _healthBar.L_HpSlot.Instance.Size = new Vector2(maxHp + 3, _healthBar.L_HpSlot.Instance.Size.Y);
  45. if (_hp > maxHp)
  46. {
  47. SetHp(maxHp);
  48. }
  49. }
  50.  
  51. /// <summary>
  52. /// 设置最大护盾值
  53. /// </summary>
  54. public void SetMaxShield(int maxShield)
  55. {
  56. _maxShield = Mathf.Max(maxShield, 0);
  57. _healthBar.L_ShieldSlot.Instance.Size = new Vector2(maxShield + 2, _healthBar.L_ShieldSlot.Instance.Size.Y);
  58. if (_shield > _maxShield)
  59. {
  60. SetShield(maxShield);
  61. }
  62. }
  63.  
  64. /// <summary>
  65. /// 设置当前血量
  66. /// </summary>
  67. public void SetHp(int hp)
  68. {
  69. _hp = Mathf.Clamp(hp, 0, _maxHp);
  70. var textureRect = _healthBar.L_HpSlot.L_HpBar.Instance;
  71. textureRect.Size = new Vector2(hp, textureRect.Size.Y);
  72. }
  73.  
  74. /// <summary>
  75. /// 设置护盾值
  76. /// </summary>
  77. public void SetShield(int shield)
  78. {
  79. _shield = Mathf.Clamp(shield, 0, _maxShield);
  80. var textureRect = _healthBar.L_ShieldSlot.L_ShieldBar.Instance;
  81. textureRect.Size = new Vector2(shield, textureRect.Size.Y);
  82. }
  83.  
  84. private void OnPlayerHpChange(object o)
  85. {
  86. SetHp(Convert.ToInt32(o));
  87. }
  88.  
  89. private void OnPlayerMaxHpChange(object o)
  90. {
  91. SetMaxHp(Convert.ToInt32(o));
  92. }
  93.  
  94. private void OnPlayerShieldChange(object o)
  95. {
  96. SetShield(Convert.ToInt32(o));
  97. }
  98. private void OnPlayerMaxShieldChange(object o)
  99. {
  100. SetMaxShield(Convert.ToInt32(o));
  101. }
  102. }