Unity 实现雷达图

下面代码实现的是上面类似的五角雷达效果

MaskableGraphic是Unity引擎中的一个接口,它用于表示可以被遮罩的图形组件。通过实现该接口,可以让一个图形组件具备遮罩的功能。

Button的点击事件来控制雷达形状

  public Ima image;
    public Button btn;
    // Start is called before the first frame update
    void Start()
    {

        btn.onClick.AddListener(() => { 
        
        List<float> list= new List<float>();
            for (int i = 0; i < 5; i++)
            {
                list.Add(Random.Range(0.1f, 100));
               

            }
            image.arr = list.ToArray();
            //重新绘制模型顶点
            image.SetVerticesDirty();

        });
    }
public class Ima : MaskableGraphic
{

    //设置一个sprite
    public Sprite activeSprite;

    //定义数组确定模型的定点数 具体信息为每个 顶点到圆心的距离 也就是半径
    public float[] arr;
    public override Texture mainTexture
    {
        get 
        {
            if (activeSprite == null)
            {
                if (material!=null&&material.mainTexture!=null)
                {
                    return material.mainTexture;
                }
                return s_WhiteTexture;//对象是默认的白色纹理
            }
            return activeSprite.texture; 
        }

        //简而言之,该属性的作用是返回一个纹理对象,如果有一个活动的Sprite,就返回该Sprite的纹理;
        //如果没有活动的Sprite,则返回材质的主纹理,如果材质的主纹理也不存在,则返回默认的白色纹理。
    }
    protected override void OnPopulateMesh(VertexHelper vh)
    {
        //如果顶点数小于三(也就是组不成三角形),那么就使用基类中的方法  基类中的方法是组成一个正方体
        if (arr.Length < 3)
        {
            base.OnPopulateMesh(vh);
            return;
        }
        //对应图形的宽和高
        float w = rectTransform.sizeDelta.x;
        float h = rectTransform.sizeDelta.y;
        //取其中半径的最大值
        float max = arr.Max();
        //散步运算确认最大边和宽高的比,如果宽长取宽,高长取高
        float p = w > h ? (w / 2) / max : (h / 2) / max;
        //清理顶点
        vh.Clear();
        //派是180度 2派是360度 求出多变体每个夹角的角度
        float angle = 2 * Mathf.PI / arr.Length;
        //定位圆点 uv取图片中心点
        vh.AddVert(Vector3.zero, color, new Vector2(0.5f, 0.5f));

        for (int i = 0; i < arr.Length; i++)
        {
            //求出除圆点之外的每条半径的坐标比
            float x = Mathf.Sin(angle * i) * arr[i] * p;
            float y = Mathf.Cos(angle * i) * arr[i] * p;
            //求出uv的坐标
            float uvx = (x + w / 2) / w;
            float uvy = (y + h / 2) / h;
            //添加除圆点外的其他顶点
            vh.AddVert(new Vector3(x, y, 0), color, new Vector2(uvx, uvy));
            if (i == 0)
            {
                vh.AddTriangle(0, arr.Length, 1);
            }
            else
            {
                vh.AddTriangle(0, i, i + 1);
            }

        }

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值