您的位置:首页 > 产品设计 > UI/UE

使用UGUI实现多层血条效果

2018-03-29 11:37 941 查看
玩过DNF的玩家应该都对这种多层血条效果不陌生



不同层数的血条拥有对应的颜色,但是颜色种类不能太多,所以当血条层数多于颜色种类数量的时候,需要按照颜色设定来重复使用血条颜色
【例如,总共设定了3种颜色:红、黄、绿,分别对应1、2、3层血条的颜色,那么当血条层数为4时,血条颜色即为红色,5时为黄色,以此类推】

实现该效果的主要思路如下:
将颜色信息保存到一个数组中,索引顺序根据颜色所对应的层数决定
计算出当前血量的血条层数
根据层数从数组里获取到对应的前景色
根据前景色来获取背景色
计算出要显示的血条长度
主要代码如下:public class MultiLayerHPCtrl : MonoBehaviour {

//背景色图片和前景色图片
public Image background;
public Image foreground;

//血条信息
public Text CurrentHPInfo;
public Text CurrentHPLayer;

//血条颜色信息数组 默认红黄绿蓝白
public Color[] hpColors = { Color.red, Color.yellow, Color.green, Color.blue, Color.white };

//一层血条的血量 默认100
public int singleLayerHP = 100;

//总血量 默认700
public int totalHP = 700;

//当前剩余血量
private int currentHP;
public int CurrentHP
{
get
{
return currentHP;
}

set
{
currentHP = value;
CurrentHPInfo.text = CurrentHP.ToString();
ShowHPLayer();
}
}

private void Start()
{
CurrentHP = totalHP;
}

/// <summary>
/// 改变血量
/// </summary>
public void ChangeHP(int num) {
CurrentHP += num;
if (CurrentHP <= 0)
{
CurrentHP = 0;
}
}

/// <summary>
/// 根据当前血量 来显示多层血条
/// </summary>
/// <param name="currentHP"></param>
private void ShowHPLayer() {
//0血的特殊情况
if (CurrentHP == 0)
{
foreground.fillAmount = 0;
CurrentHPLayer.text = "0";
return;
}

//首先计算出当前血量是第几层血
int layerNum = CurrentHP / singleLayerHP;
//无法整除的情况下多加1层(例如550血需要显示第6层)
if (CurrentHP % singleLayerHP != 0)
{
layerNum++;
}
CurrentHPLayer.text = layerNum.ToString();

//根据层数获取对应前景色
int foregroundColorIndex = (layerNum % hpColors.Length) - 1;
//层数是颜色数组长度的整数倍时,颜色为最后1种颜色
if (foregroundColorIndex == -1)
{
foregroundColorIndex = hpColors.Length - 1;
}
foreground.color = hpColors[foregroundColorIndex];

//根据前景色获取对应背景色
//只剩最后1层血时,背景色固定为黑色
if (layerNum == 1)
{
background.color = Color.black;
}
else
{
int backgroundColorIndex;
if (foregroundColorIndex != 0)
{
//前景色索引不为0就倒退1位(x不为0时,x层的背景色=x-1层的前景色)
backgroundColorIndex = foregroundColorIndex - 1;
}
else
{
//否则为最后1位
backgroundColorIndex = hpColors.Length - 1;
}

background.color = hpColors[backgroundColorIndex];
}

//计算出要显示的血条长度
float length = 1.0f *(CurrentHP % singleLayerHP) / singleLayerHP;
//当前血量是一层血条代表血量的整数倍时,显示长度为100%
if (length == 0)
{
length = 1;
}
//改变长度
foreground.fillAmount = length;

}

}
监听按钮点击事件的代码如下:public class ChangeHP : MonoBehaviour {

public MultiLayerHPCtrl ctrl;

public void OnClick() {
ctrl.ChangeHP(-10);
}
}最终效果演示:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: