Unity 制作游戏对象血条,利用场景物体Quad

主要利用血量百分比实现对红绿血条的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;
    }
}

具体效果:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值