013. mesh 圆形

2020-03-01  本文已影响0人  cmd_ts
03.png 032.png
MeshFilter mesh_filter = gameObject.AddComponent<MeshFilter>();
        MeshRenderer mesh_renderer =  gameObject.AddComponent<MeshRenderer>();
        // gameObject.GetComponent<MeshRenderer>().material 
        Mesh mesh = mesh_filter.mesh;
        mesh.Clear();
        //设置顶点 N个顶点,就会有N-1个三角形
        float radius = 1;   //圆的半径
        int segments = 64;  //设置有64个三角形
        Vector3[] vertices = new Vector3[segments + 1];
        Vector3 centerCircle = new Vector3(0,0,0);
        vertices[0] = centerCircle;
        //Mathf.Deg2Rad 度转弧度:Mathf.Deg2Rad = (PI * 2) / 360
        float deltaAngle = Mathf.Deg2Rad * 360f / segments;
        float currentAngle = 0;
        //设置三角形顶点顺序,顺时针设置
        for (int i = 1; i < vertices.Length; i++)
        {
            float cosA = Mathf.Cos(currentAngle);
            float sinA = Mathf.Sin(currentAngle);
            vertices[i] = new Vector3(cosA * radius + centerCircle.x, sinA * radius + centerCircle.y, 0);
            currentAngle += deltaAngle;
        }

        //顶点
        int[] triangles = new int[segments * 3];
        //0,2,1 0,3,2 0,4,3 0,5,4 ..... 0,1,N
        for (int i = 0, j = 1; i < segments * 3 - 3; i += 3, j++)
        {
            triangles[i] = 0;
            triangles[i + 1] = j + 1;
            triangles[i + 2] = j;
        }
        triangles[segments * 3 - 3] = 0;
        triangles[segments * 3 - 2] = 1;
        triangles[segments * 3 - 1] = segments;

        mesh.Clear();
 
        mesh.vertices = vertices;
        mesh.triangles = triangles;
上一篇下一篇

猜你喜欢

热点阅读