雷达图的定义:雷达图是以从同一点开始的轴上表示的三个或更多个定量变量的二维图表的形式显示多变量数据的图形方法。
雷达图在游戏中经常被用来更直观的展示角色属性及各种信息
怎么在unity中实现雷达图:
了解MaskableGraphic类:
MaskableGraphic继承自UI.Graphic,作用是绘制够被遮罩的Graphic。
创建空对象以及雷达图脚本,脚本继承MaskableGraphic类,通过重写OnPopulateMesh方法进行雷达图的制作:
protected override void OnPopulateMesh(VertexHelper vh)
{
if (arr.Length < 3)
{
base.OnPopulateMesh(vh);
}
vh.Clear();
float ang = 2 * Mathf.PI / arr.Length;
float w = rectTransform.sizeDelta.x;
float h = rectTransform.sizeDelta.y;
vh.AddVert(Vector3.zero, color, Vector2.one * 0.5f);
for (int i = 0; i < arr.Length; i++)
{
float x = Mathf.Sin(i * ang) * arr[i];
float y = Mathf.Cos(i * ang) * arr[i];
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);
}
}
}
数组arr中储存了雷达图每个顶点所代表的信息的数值,根据数组中值的数量正确计算每个角弧度
,然后再弧度与半径正确计算出每个顶点的位置,但是这样绘制可能会超出ui,所以要对数值进行限制或者对数值进行等比计算:
//计算最大值与矩形较长边的比值
float max = arr.Max();
float p = w < h ? w / 2 / max : h / 2 / max;
//在计算坐标时乘以这个比值
float x = Mathf.Sin(i * ang) * arr[i] * p;
float y = Mathf.Cos(i * ang) * arr[i] * p;
游戏中的数值会发生改变,可以做一个按钮生成随机值进行测试进行 :
protected override void Awake()
{
m = 4;
arr = new float[5] { 200, 200, 200, 200, 200 };
if (button != null)
{
button.onClick.AddListener(() =>
{
for (int i = 0; i < 5; i++)
{
arr[i] = Random.Range(1, 200);
}
SetVerticesDirty();
});
}
}
每次点击按钮对数值数组重新赋值,然后调用SetVerticesDirty函数重新绘制图形,效果如下:
最后可以再加一些描边效果:
//画描边
int next = arr.Length + 1;
for (int i = 0; i < arr.Length; i++)
{
float x0 = Mathf.Sin(i * ang) * (arr[i] * p - m);
float y0 = Mathf.Cos(i * ang) * (arr[i] * p - m);
float uvx0 = (x0 + w / 2) / w;
float uvy0 = (y0 + h / 2) / h;
vh.AddVert(new Vector3(x0, y0, 0), mcolor, new Vector2(uvx0, uvy0));
float x = Mathf.Sin(i * ang) * (arr[i] * p);
float y = Mathf.Cos(i * ang) * (arr[i] * p);
float uvx = (x + w / 2) / w;
float uvy = (y + h / 2) / h;
vh.AddVert(new Vector3(x, y, 0), mcolor, new Vector2(uvx, uvy));
if (i == arr.Length-1)
{
vh.AddTriangle(i * 2 + next, i * 2 + 1 + next, 1+next);
vh.AddTriangle(i * 2 + next, 1 + next, next);
}
else
{
vh.AddTriangle(i*2+next,i*2+1+next,(i+1)*2+1+next);
vh.AddTriangle(i * 2 + next, (i + 1) * 2 + 1 + next, (i + 1) * 2 + next);
}
}
描边效果的原理就是在雷达图周围用Mesh再绘制一圈网格。