很久沒寫文章了。那天有人問我遊戲人物血條如何慢慢減掉。今天寫一下吧。首先上個動態圖,看效果: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!圖片