You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
58 lines
1.5 KiB
58 lines
1.5 KiB
using UnityEngine;
|
|
using BigFloatNumerics;
|
|
|
|
public class HpBarHandler : MonoBehaviour, IOwnedComponent<Character>
|
|
{
|
|
[SerializeField] Transform spawnPosition;
|
|
[SerializeField] ExtendSlider barPrefab;
|
|
|
|
public Character Owner { get; private set; }
|
|
|
|
StatData hpStat;
|
|
|
|
Camera mainCamera;
|
|
Camera uiCamera;
|
|
RectTransform barRoot;
|
|
|
|
ExtendSlider barInstance;
|
|
|
|
public void Initialize(Character owner)
|
|
{
|
|
Owner = owner;
|
|
Owner.Data.TryGetStat(StatID.Hp, out hpStat);
|
|
|
|
mainCamera = Camera.main;
|
|
uiCamera = GameObject.FindGameObjectWithTag("UICamera").GetComponent<Camera>();
|
|
barRoot = GameObject.FindGameObjectWithTag("HpBarRoot").GetComponent<RectTransform>();
|
|
|
|
barInstance = Instantiate(barPrefab, barRoot);
|
|
}
|
|
|
|
private void OnDestroy()
|
|
{
|
|
if (Owner == null) return;
|
|
|
|
if(barInstance != null && barInstance.gameObject != null)
|
|
Destroy(barInstance.gameObject);
|
|
}
|
|
|
|
private void Update()
|
|
{
|
|
if (barInstance == null) return;
|
|
|
|
if (Owner != null && hpStat != null)
|
|
{
|
|
barInstance.SetRate((BigFloat)Owner.CurrentHp / hpStat.Value);
|
|
}
|
|
}
|
|
|
|
private void LateUpdate()
|
|
{
|
|
if(barInstance == null) return;
|
|
|
|
var screenPos = mainCamera.WorldToScreenPoint(spawnPosition.position);
|
|
RectTransformUtility.ScreenPointToLocalPointInRectangle(barRoot, screenPos, uiCamera, out Vector2 localPos);
|
|
|
|
barInstance.transform.localPosition = localPos;
|
|
}
|
|
}
|