unity制作类似DNF动态血条(仅一层血条)

在这里插入图片描述
unity制作类似DNF动态血条(仅一层血条)

这是某个游戏公司的招聘题目,我的思路给大家参考一下
上图为效果图

如下代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class dynamichealth : MonoBehaviour
{
    public Image greenhealthBar;//表面血条
    public Image grayhealthBar;//动态平滑血条
    public Text grayhealthBar;//血量数值

    public float maxhealth = 100f;//最大血量
    public float currenthealth;//目前血量
    public float damage;//伤害值
    public float nowTargetValue;//剩余血量比例

    public bool ison=false;
  
    void Awake()
    {
    }
    void Start()
    {
        currenthealth = maxhealth;
    }

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            ison = true;
            damage= Random.Range(1, 10);
            currenthealth -= damage;
            healthText.text = currenthealth + "/" + maxhealth;//显示血量值
            nowTargetValue = currenthealth / maxhealth;
        }
        if (ison == true)
        {
            TakeDamage();
        }
    }
    
    void TakeDamage()
    {
        greenhealthBar.fillAmount= currenthealth / maxhealth;
        grayhealthBar.fillAmount = Mathf.Lerp(grayhealthBar.fillAmount, nowTargetValue, 0.1f);//Lerp插值函数用于平滑显示血条
    }
}

记住要把ImageType的Filled 横向,类似于下面这样
在这里插入图片描述
记得再把greenhealthBar,grayhealthBar,grayhealthBar填入unity

我的这个实现很简陋,最后还没有设定边界,希望大家可以更加优化一下。
关于代码中的fillAmount,它就是上图中的Fill Amount。其值要为float类型。
关于Lerp函数,可以自行百度哈。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值