Files
Hasebe/Assets/Code/OfficeGame/BattleMode/Health/UI/EntityHealthPanel.cs
T
2026-11-17 18:44:54 +03:00

105 lines
2.8 KiB
C#

using System;
using System.Threading;
using Code.Infrastructure.Camera;
using Code.Infrastructure.UI;
using Cysharp.Threading.Tasks;
using R3;
using Reflex.Attributes;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
namespace Code.OfficeGame.BattleMode.Health.UI
{
public class EntityHealthPanel : UIPanel
{
[SerializeField] private TMP_Text healthText;
[SerializeField] private Image healthBar;
[SerializeField] private Color criticalColor;
[SerializeField] private Color fullColor;
[SerializeField] private Color deadColor;
[SerializeField]
[Range(0.1f,0.9f)]
private float criticalPercent;
private DisposableBag _healthSubscriptions;
private Camera _camera;
private Transform _target;
[Inject]
public void Construct(CameraStateMachine cameraStateMachine)
{
_camera = cameraStateMachine.Camera;
}
private void LateUpdate()
{
if (!_target || !_camera) return;
Vector3 screenPos = _camera.WorldToScreenPoint(_target.position);
bool isVisible = screenPos.z > 0;
if (gameObject.activeSelf != isVisible)
gameObject.SetActive(isVisible);
if (isVisible)
transform.position = screenPos;
}
public void SetTarget(Transform target)
{
_target = target;
}
public void SubscribeHealthPanel(EntityHealth entityHealth)
{
entityHealth.HealthData
.Subscribe(SetHealthStatus)
.AddTo(ref _healthSubscriptions);
}
private void SetHealthStatus(HealthData healthData)
{
if (healthData.CurrentHealth <= 0)
{
healthText.color = deadColor;
healthText.SetText("Dead");
healthBar.fillAmount = 1;
return;
}
float healthPercentage = (float)healthData.CurrentHealth / healthData.MaxHealth;
healthBar.fillAmount = healthPercentage;
// SB
healthText.SetText($"{healthData.CurrentHealth}/{healthData.MaxHealth}");
if (healthPercentage <= criticalPercent)
healthBar.color = criticalColor;
else
healthBar.color = fullColor;
}
public override UniTask Open(CancellationToken cts = default)
{
gameObject.SetActive(true);
return UniTask.CompletedTask;
}
public override UniTask Close(CancellationToken cts = default)
{
gameObject.SetActive(false);
return UniTask.CompletedTask;
}
private void OnDestroy()
{
_healthSubscriptions.Dispose();
}
}
}