要求:实现按下某一按键血条块与血量数值增加或者减少
实现:先创建两个UI->Image,红色表示血条在上,黑色在下。
点击红色血条,在属性一栏中将Fill Method改为Horizontal(水平)
通过修改Fill Amount来控制血条的消失与增加
具体实现代码如下
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class L8HP : MonoBehaviour
{
//设置初始血量 100点血
//如果按下K键,受到一次打击,掉10点血
float hp = 100;//最大血量
float currentHp;
Image bloodImage;
Text bloodText;
float ratio;//当前的比例值
void Start()
{
currentHp = hp;
ratio = currentHp/hp ;//当前比例值
bloodImage = GetComponent<Image>();
bloodText = GetComponentInChildren<Text>();
//设置初始血量数值
bloodText.text = currentHp.ToString();
}
void Update()
{
if (Input.GetKeyDown(KeyCode.K))
{
Addhp(-10);
}
if (Input.GetKeyDown(KeyCode.Space))
{
Addhp(10);
}
//实现慢慢减血
bloodImage.fillAmount = Mathf.Lerp(bloodImage.fillAmount, ratio, Time.deltaTime * 5);
//当前血量值
bloodText.text = Mathf.RoundToInt(bloodImage.fillAmount * hp).ToString();
}
void Addhp(float addhp){
currentHp += addhp;
currentHp = Mathf.Clamp(currentHp, 0, hp);
ratio = currentHp / hp;//更新当前血量比例
Debug.Log("当前血量为" + currentHp);
}
}
将写好的代码挂载到红色血条上