using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class TestHp : 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.wh;
}
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 void OnClick()
{
ChangeHP(-30);
}


}