如何实现WASD键控制血条蓝条的加减、血量的加减?代码不难理解,空闲时整理了出来,时间仓促,有需要的小伙伴可自行下载。
血条、蓝条:AD控制血条是否满格、WS控制蓝条的大小
using UnityEngine.UI;
public class MPCtrl : MonoBehaviour {
//血条最大值
public float hpMax = 1000;
//蓝条最大值
public float mpMax = 500;
//血条蓝条增减速度
public float speed=3f;
//血条
private RectTransform hpTra;
//蓝条
private RectTransform mpTra;
//血条文本
private Text hpText;
//蓝条文本
private Text mpText;
// Use this for initialization
//横纵轴
private float h, v;
//血条图片宽度
private float hpWidth;
//蓝条图片宽度
private float mpWidth;
void Start () {
//获取血条内容
hpTra = transform.Find("HPImage/BackgroundImage")as RectTransform;
//hpText = hpTra.GetChild(0).GetComponent
hpText = transform.Find("HPImage/BackgroundImage/Text").GetComponent<Text>();
//获取蓝条内容
mpTra = transform.Find("MPImage/BackgroundImage") as RectTransform;
mpText = transform.Find("MPImage/BackgroundImage/Text").GetComponent<Text>();
//获取血条蓝条图片宽度
hpWidth = hpTra.rect.width;
mpWidth = mpTra.rect.width;
}
// Update is called once per frame
void Update () {
//获取两轴
h = Input.GetAxis("Horizontal");
v=Input.GetAxis("Vertical");
//调整血条
UIAdjust(hpTra, hpText, hpWidth, hpMax, h);
//调整蓝条
UIAdjust(mpTra, mpText, mpWidth, mpMax, v);
}
///
/// 调整UI
///
/// ">UI的RectTransform
/// ">文本
/// ">最大宽度
/// ">最大值
/// ">轴
void UIAdjust(RectTransform tra,Text text,float maxWidth,float maxValue,float axis)
{
//如果玩家开始调整UI
if (axis != 0)
{
//当前UI宽度
float currentWidth = tra.sizeDelta.x + Time.deltaTime * axis * speed;
//限制后UI的宽度
currentWidth =Mathf.Clamp(currentWidth, 0, maxWidth);
//调整UI的宽度
tra.sizeDelta = new Vector2(currentWidth, tra.sizeDelta.y);
//计算当前的值
float currentValue = currentWidth / maxWidth * maxValue;
//将值更新当文本中
text.text = Mathf.Round(currentValue).ToString() + "/" + maxValue.ToString();
}
}
}