这个函数用来实现两个分段区间之间的映射,假设有A,B两个分段区间的定义,给定一个在A内的值,可以求得在B内的相对起始点的百分比。
两个区间的分段个数需要一致,数组的第一个元素固定为0,最后一个元素为最后一个区间的最大值。
public static float remap(float[] srcmap, float[] tomap, float refval)
{
if(srcmap.Length!=tomap.Length)
{
//Debug.log("映射区间数量不匹配!{0},{1}", srcmap.Length, tomap.Length);
return -1;
}
if (refval < srcmap[0]) return 0;
if (refval > srcmap[srcmap.Length - 1]) return 1;
float tomax = tomap[tomap.Length - 1];
int rank = 0;
float srcSubPercent = 0;
for(int i=0; i<srcmap.Length-1; i++)
{
if(refval>srcmap[i] && refval < srcmap[i + 1])
{
rank = i;
srcSubPercent = (refval - srcmap[i]) / (srcmap[i + 1] - srcmap[i]);
break;
}
}
float basePercent = tomap[rank] / tomax;
float subPercent = (tomap[rank + 1] - tomap[rank]) / tomax * srcSubPercent;
return basePercent + subPercent;
}