很久没写文章了。那天有人问我游戏人物血条如何慢慢减掉。今天写一下吧。首先上个动态图,看效果:this
在以前的文章中讲过如何实现技能冷却的效果(上图中技能冷却效果),血条的慢慢减少原理和技能冷却的是同样的。spa
下面是具体步骤: code
1.首先先新建一个scrollbar 做为血条,而后把 Handle的颜色改为红色,而且把ImageType改为Filled.,把填充方式改为水平的(见下图:)
2.而后开始用脚本控制血条
我脚本绑定的位置是技能冷却的图片,而后把Handle拖到指定位置(以下图:)
技能冷却代码和血条渐渐减少代码以下blog
(代码中写了详细的注释这里再也不赘述):游戏
1 using UnityEngine; 2 using System.Collections; 3 using UnityEditor; 4 using UnityEngine.UI; 5 public class skillcd : MonoBehaviour 6 { 7 public Image hps; 8 private Image spcd; 9 private bool cooling, hpstart; 10 private float hurt = 0.2f, all = 1; 11 // Use this for initialization 12 void Start() 13 { 14 hps.fillAmount = 1f;//血量 15 16 spcd = this.GetComponent<Image>();//获取组件方法 17 spcd.fillAmount = 0;//冷却值 18 } 19 20 // Update is called once per frame 21 void Update() 22 { 23 if (cooling == false && Input.GetKeyDown(KeyCode.R))//放技能 24 { 25 26 hpstart = true; 27 spcd.fillAmount = 1f; 28 cooling = true;//冷却条件 29 30 31 } 32 33 if (cooling) 34 { 35 36 spcd.fillAmount -= 0.2f * Time.deltaTime; 37 if (spcd.fillAmount < 0.01f)//冷却完毕 38 { 39 spcd.fillAmount = 0; 40 cooling = false; 41 } 42 } 43 44 45 //血量逻辑开始 46 if (hpstart) 47 { 48 Debug.Log("血量:" + hps.fillAmount); 49 50 hps.fillAmount = (hps.fillAmount -= 0.1f * Time.deltaTime) * hps.fillAmount / (hps.fillAmount); 51 52 if (hps.fillAmount <= (all - hurt))//当前血量值 小于等于 目标血量值 53 { 54 Debug.Log("ting"); 55 56 hpstart = false; 57 all = hps.fillAmount;//总血量值 被赋值 当前血量值 58 } 59 60 Debug.Log("血量2:" + hps.fillAmount); 61 } 62 } 63 }
就这样就实现了这个功能,So Easy!图片