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

    科技2022-08-24  105

    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函数,可以自行百度哈。

    Processed: 0.019, SQL: 9