Unity仿真 液位计温度计等

效果:

 

using System;
using System.Collections.Generic;
using UnityEngine;
public class Main : MonoBehaviour
{
    [Range(0, 100)]
    public float level; // 用户输入的数值
    public List levelScales; // 用户配置的结构体列表 
    private void Start()
    { 
        // 按液位数值从小到大排序
        levelScales.Sort((a, b) => a.level.CompareTo(b.level));
    }
    private void Update()
    {
        SetBar(level);
    }
    void SetBar(float _current)
    {
        // 使用二分查找算法找到对应的缩放值
        int index = BinarySearch(levelScales, _current);
        float scaleRatio = 0; 
        if (index==-1)
        {
            scaleRatio = 0;
        }
        else
        {
            scaleRatio = Mathf.Lerp(levelScales[index].scale, levelScales[index + 1].scale, (_current - levelScales[index].level) / (levelScales[index + 1].level - levelScales[index].level));
        }

        // 将缩放比例转换为液位计模型上的Y轴坐标 
        // 更新液位计模型的Y轴缩放值
        Vector3 newScale = transform.localScale;
        newScale.y = scaleRatio;
        transform.localScale = newScale;
    }
    // 二分查找算法
    private int BinarySearch(List list, float level)
    {
        if (list.Count<2)
        {
            return -1;
        }
        int min = 0;
        int max = list.Count - 2;
        int mid = 0;
        while (min <= max)
        {
            mid = (min + max) / 2;
            if (level < list[mid].level)
            {
                max = mid - 1;
            }
            else if (level > list[mid + 1].level)
            {
                min = mid + 1;
            }
            else
            {
                return mid;
            }
        }
        return mid;
    }
}
// 结构体,用于存储液位数值和数值对应的缩放值
[Serializable]
public struct LevelScale
{
    public float level;
    public float scale;
}

你可能感兴趣的:(unity,游戏引擎,c#)