下面代码实现的是上面类似的五角雷达效果
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);
}
}
}
}