using Godot; namespace ColdMint.scripts; public partial class HealthBarUi : HBoxContainer { private int _maxHp; private int _currentHp; public int CurrentHp { get => _currentHp; set { if (value == _currentHp) { return; } var heartCount = GetChildCount(); //有几颗心是满的 var fullHeartCount = value / Config.HeartRepresentsHealthValue; for (int i = 0; i < fullHeartCount; i++) { //把Ui刷满 var textureRect = GetChild(i); textureRect.Texture = _heartFull; } //有多少空心 var emptyHeartCount = heartCount - fullHeartCount; //最后那颗剩余多少血 var leftOverTextureRect = GetChild(fullHeartCount); var leftOver = value % Config.HeartRepresentsHealthValue; if (leftOver > 0) { //占总数的百分比 var percent = leftOver / (float)Config.HeartRepresentsHealthValue; leftOverTextureRect.Texture = GetTexture2DByPercent(percent); emptyHeartCount--; } for (int i = heartCount - emptyHeartCount; i < heartCount; i++) { var textureRect = GetChild(i); textureRect.Texture = _heartEmpty; } _currentHp = value; } } public int MaxHp { get => _maxHp; set { if (value == _maxHp) { return; } var heartCount = value / Config.HeartRepresentsHealthValue; for (var i = 0; i < heartCount; i++) { var heart = CreateTextureRect(); heart.Texture = _heartFull; AddChild(heart); } //最后那颗剩余多少血 var leftOver = value % Config.HeartRepresentsHealthValue; if (leftOver > 0) { var lastHeart = CreateTextureRect(); //占总数的百分比 var percent = leftOver / (float)Config.HeartRepresentsHealthValue; lastHeart.Texture = GetTexture2DByPercent(percent); AddChild(lastHeart); } _maxHp = value; } } private TextureRect CreateTextureRect() { var textureRect = new TextureRect(); return textureRect; } /// /// Get the texture based on percentage /// 根据百分比获取纹理 /// /// /// private Texture2D GetTexture2DByPercent(float percent) { if (percent == 0) { return _heartEmpty; } if (percent <= 0.25f) { return _heartQuarter; } else if (percent <= 0.5f) { return _heartHalf; } else if (percent <= 0.75f) { return _heartThreeFourths; } else { return _heartFull; } } private Texture2D _heartFull; private Texture2D _heartEmpty; private Texture2D _heartHalf; private Texture2D _heartQuarter; private Texture2D _heartThreeFourths; public override void _Ready() { base._Ready(); _heartEmpty = GD.Load("res://sprites/ui/HeartEmpty.png"); _heartQuarter = GD.Load("res://sprites/ui/HeartQuarter.png"); _heartHalf = GD.Load("res://sprites/ui/HeartHalf.png"); _heartThreeFourths = GD.Load("res://sprites/ui/HeartThreeFourths.png"); _heartFull = GD.Load("res://sprites/ui/HeartFull.png"); } }