Unity 不规则进度条显示
using System.Collections;
using System.Collections.Generic;
using System.Text;
using TMPro;
using UniRx;
using UnityEngine;
using UnityEngine.UI;
public class Power : MonoBehaviour
{
//功率百分比
[SerializeField] private TextMeshProUGUI PowerValueText;
//功率输出0~100%
[SerializeField] private Image Img_PowerOutput;
//能量回收-25%~0
[SerializeField] private Image Img_EnergyRecovery;
//功率输出范围(Vector2[真实值,显示进度条位置])
[SerializeField] private List _power = new List();
//能量回收范围(Vector2[真实值,显示进度条位置])
[SerializeField] private List _energy = new List();
private static readonly string TAG = "Power";
private void Start()
{
//当前功率
DataCenter.Power.Subscribe(f =>
{
Log.I(TAG, "Power select value: " + f);
PowerValueText.text = f.ToString("0");
if (f >= 0)
{
Img_EnergyRecovery.fillAmount = 0;
Vector4 vector = GetLerpValue(f, ref _power);
Img_PowerOutput.fillAmount = Mathf.Lerp(vector.x, vector.y, (Mathf.Abs(f) - vector.z) / (vector.w - vector.z));
}
else
{
Img_PowerOutput.fillAmount = 0;
Vector4 vector = GetLerpValue(f, ref _energy);
Img_EnergyRecovery.fillAmount = Mathf.Lerp(vector.x, vector.y, (Mathf.Abs(f) - vector.z) / (vector.w - vector.z));
}
}).AddTo(this);
}
private Vector4 GetLerpValue(float value, ref List<Vector2> values)
{
Vector2 min = values[0];
Vector2 max = values[values.Count - 1];
float minX = Mathf.Abs(min.x), maxX = Mathf.Abs(max.x), valueAbs = Mathf.Abs(value);
if (valueAbs >= minX && valueAbs <= maxX)
{
for (int i = 1; i < values.Count; i++)
{
Vector2 start = values[i - 1];
Vector2 end = values[i];
float startX = Mathf.Abs(start.x), endX = Mathf.Abs(end.x);
if (valueAbs >= startX && valueAbs <= endX)
{
return new Vector4(start.y, end.y, startX, endX);
}
}
}
return new Vector4(min.y, max.y, minX, maxX);
}
}