雷达图一般都是显示在UGUI上,但在开始写时创建出来的是3D物体,走了点弯路才发现CanvasRenderer。
CanvasRenderer与3D世界模型的'Mesh Render'一样,UGUI的UI元素也需要一个Render渲染出来,那么第一时间想到的就是修改Render的Mesh。
具体的操作
因为5变形的角度都是一样的,旋转的角度是360/(边数-1)。
通过一个Vector3.up沿着指定的角度旋转,来确定5个边的顶点的位置,中心点为一个顶点。我们就把顶点的位置赋值完毕。
在赋值三角面时,我们需要了解:
顶点顺时针,剔除后面
顶点逆时针,剔除前面
同时绘制顶点顺时针与顶点逆时针 ,两面都可以看
当我们完成mesh的创建后,我们需要赋值给UGUI的Mesh,必须赋值材质,不然看不到创建出来的UI
canvasRenderer.SetMesh(mesh);
canvasRenderer.SetMaterial(renderMaterial, null);
现在UI在game场景中显示的材质是不对的。这是正常状态。因为设置mesh的uv和切线都没写
Image.gif
代码:
private int[] triangles;
private Vector2[] uvs;
private Vector3[] vertices;
private Vector4[] tangents;
[Header("元素")]
public float element1 = 10;
public float element2 = 10;
public float element3 = 10;
public float element4 = 10;
public float element5 = 10;
private float sideLength = 10;
private float everyAngle=0;
private CanvasRenderer canvasRenderer;
[SerializeField]
private Material renderMaterial;
private int count = 6;
private Mesh mesh;
void Start()
{
SetVertices();
}
private void Update()
{
for (int i = 1; i < vertices.Length; i++)
{
switch (i)
{
case 1:
sideLength = element1;
break;
case 2:
sideLength = element2;
break;
case 3:
sideLength = element3;
break;
case 4:
sideLength = element4;
break;
case 5:
sideLength = element5;
break;
}
vertices[i] = Quaternion.Euler(0, 0, everyAngle * i) * Vector3.up * sideLength;
}
mesh.vertices = vertices;
canvasRenderer.SetMesh(mesh);
}
void SetVertices()
{
canvasRenderer = GetComponent<CanvasRenderer>();
mesh = new Mesh();
vertices = new Vector3[count];
uvs = new Vector2[count];
triangles = new int[count * 3];
tangents = new Vector4[count];
Vector4 tangent = new Vector4(0, 1, 0, -1);
everyAngle = (float)360 / (count-1);
for (int i = 0; i < vertices.Length; i++) //循环顶点
{
vertices[i] = Quaternion.Euler(0, 0, everyAngle * i) * Vector3.up * sideLength;
uvs[i] = Quaternion.Euler(0, 0, everyAngle * i) * Vector3.up;
tangents[i] = tangent;
}
for (int i = 0, index=0; i < count-1; i++,index+=3)
{
triangles[index + 0] = 0;
triangles[index + 1] = i==4?1:2+i;
triangles[index + 2] = i==4?5:1+i;
}
mesh.vertices = vertices;
mesh.triangles = triangles;
mesh.RecalculateNormals();
mesh.tangents = tangents;
mesh.uv = uvs;
canvasRenderer.SetMesh(mesh);
canvasRenderer.SetMaterial(renderMaterial, null);
}
网友评论