主要利用血量百分比实现对红绿血条的x轴的百分比变化。
核心代码:
public class HealthBar : MonoBehaviour
{
/// <summary>
///挂载到减少血条物体上 我们改变其X-scale以减少血条
/// </summary>
[SerializeField] public Transform healthBar;
/// <summary>
/// 挂载到增血条物体上 我们改变其X-scale以增加血条
/// </summary>
[SerializeField]public Transform backgroundBar;
/// <summary>
/// 血条是否是满的
/// </summary>
public bool showWhenFull;
/// <summary>
/// 面向的摄像头
/// </summary>
protected Transform m_CameraToFace;
/// <summary>
///更新血量
/// </summary>
/// <param name="normalizedHealth">百分比血量值</param>
public void UpdateHealth(float normalizedHealth)
{
Vector3 scale = Vector3.one;
if (healthBar != null)
{
scale.x = normalizedHealth;
healthBar.transform.localScale = scale;
}
if (backgroundBar != null)
{
scale.x = 1 - normalizedHealth;
backgroundBar.transform.localScale = scale;
}
SetVisible(showWhenFull || normalizedHealth < 1.0f);
}
/// <summary>
///显示隐藏血条
/// </summary>
public void SetVisible(bool visible)
{
gameObject.SetActive(visible);
}
protected virtual void Start()
{
m_CameraToFace = UnityEngine.Camera.main.transform;
}
/// <summary>
///面向摄像机
/// </summary>
protected virtual void Update()
{
Vector3 direction = m_CameraToFace.transform.forward;
transform.forward = -direction;
}
}
具体效果: