CockHpComp.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. using System;
  2. using UnityEngine;
  3. using UnityEngine.UI;
  4. namespace Comp
  5. {
  6. public class CockHpComp : MonoBehaviour
  7. {
  8. // 血量条组件
  9. private Image _backgroundImage, _foregroundImage;
  10. private int _maxHp, _curHp;
  11. public int reduceHp; // 需要扣除的Hp
  12. private ParticleSystem _particleSystem;
  13. public int MaxHp
  14. {
  15. set
  16. {
  17. _maxHp = value;
  18. _curHp = _maxHp;
  19. }
  20. }
  21. private void ReduceCurHp(int hp)
  22. {
  23. _curHp -= hp;
  24. var hpPercent = (float)_curHp / _maxHp;
  25. if (hpPercent > 0.5f)
  26. {
  27. _foregroundImage.color = Color.green;
  28. }
  29. else if (hpPercent is >= 0.25f and <= 0.5f)
  30. {
  31. _foregroundImage.color = Color.yellow;
  32. }
  33. else
  34. {
  35. _foregroundImage.color = Color.red;
  36. }
  37. var backgroundSize = _backgroundImage.rectTransform.sizeDelta;
  38. var foregroundSize = _foregroundImage.rectTransform.sizeDelta;
  39. var newForegroundWidth = backgroundSize.x * hpPercent;
  40. _foregroundImage.rectTransform.sizeDelta = new Vector2(newForegroundWidth, foregroundSize.y);
  41. _particleSystem.Play(); // 播放粒子特效
  42. }
  43. private void Awake()
  44. {
  45. _particleSystem = GetComponentInChildren<ParticleSystem>();
  46. }
  47. private void Start()
  48. {
  49. // 获取血条的填充图片
  50. var images = GetComponentsInChildren<Image>();
  51. foreach (var image in images)
  52. {
  53. if (image.name == "Background")
  54. {
  55. _backgroundImage = image;
  56. }
  57. if (image.name == "Foreground")
  58. {
  59. _foregroundImage = image;
  60. }
  61. }
  62. }
  63. private void Update()
  64. {
  65. if (reduceHp != 0)
  66. {
  67. ReduceCurHp(reduceHp);
  68. reduceHp = 0;
  69. }
  70. }
  71. }
  72. }