unity2d人物頭頂設置血條實現

unity2d人物頭頂設置血條實現

ui->image//加入ui圖片顯示
在這裏插入圖片描述
拖入白色血條圖片,設置width200,height20
image tape 設置爲filled
顏色設置爲紅色
在這裏插入圖片描述
注意!!!!這裏按着alt建選擇middle的靠左邊的那個,因爲這是設置錨點,最左邊之後我們可以通過設置width讓血量減少
複製粘貼一份形成兩個image節點,另一個顏色爲白色,作爲底下的背景

創建ui->按鈕,然後讓按鈕的位置大小和血條一樣,方便我們後面設計鼠標點擊後血量減少
在這裏插入圖片描述
記得設置透明度爲0,讓按鈕不顯示
創建c#代碼,命名xuetiao,內容如下

public class xuetiao : MonoBehaviour
{
    // Start is called before the first frame update
    public GameObject my;
    public float speed = 5.0f;
    bool conctol = false;
    void Start()
    {
        my.GetComponent<Button>().onClick.AddListener(delegate ()
        {
            conctol =true;
        }
         );
       
    }
    // Update is called once per frame
    void Update()
    {
        if (conctol)
            StartCoroutine(Changeblood());
    }
    IEnumerator Changeblood()
    {
       
          yield return  null;//停止執行方法time秒,下一幀從這裏開始return new waitforsecong(time);
            this.GetComponent<RectTransform>().sizeDelta = Vector2.Lerp(this.GetComponent<RectTransform>().sizeDelta, new Vector2(0, this.GetComponent<RectTransform>().sizeDelta.y), speed * Time.deltaTime/10.0f );
        
    }
}

*lerp是一個插入值的函數Lerp 插值

static functionLerp (from : Vector2, to : Vector2, t : float) : Vector2

兩個向量之間的線性插值。按照數字t在form到to之間插值。

t是夾在0到1之間。當t=0時,返回from。當t=1時,返回to。當t=0.5時放回from和to之間的平均數。*
代碼加到紅的血條上面
在這裏插入圖片描述
這裏拖進去剛纔的按鈕組件
然後運行,點擊血條,會看到血條逐漸下降
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章