怎么绘制属于自己网格信息

unity里面一个物体要渲染出来 需要两个组件 一个是MeshFilter 一个是MeshRender

一个mesh 想要绘制出来需要设置的信息:

//这两个是必须的
vertices : 定点坐标
tangents: 三角形坐标索引

//可有可无的
uv: uv贴图
tangents : 法线贴图 左下角是 0,0点 最大是 1,1 点

tangents:
在unity中是顺时针存储,如果逆时针的话 只能在物体内部看见

怎么绘制属于自己网格信息_第1张图片

//绘制过程:
1,绘制顶点坐标
2,根据顶点坐标设置三角形3个顶点坐标
3,设置UV
4,设置发现
//后面两部并不是都需要

    private Vector3[] vertices;

    public int xSize = 10;
    public int ySize = 5;

    private Mesh mesh;

    void Awake()
    {
        Generate();
    }

    private void Generate()
    {

        this.GetComponent().mesh = mesh = new Mesh();

        vertices = new Vector3[(xSize + 1) * (ySize + 1)];
        //法线信息
        Vector4[] tangents = new Vector4[vertices.Length];
        Vector4 tangent = new Vector4(1f, 0f, 0f, -1f);

        Vector2[] uv = new Vector2[vertices.Length]; //控制UV贴图
        for (int i = 0, y = 0; y <= ySize; y++)
        {
            for (int x = 0; x <= xSize; x++, i++)
            {
                vertices[i] = new Vector3(x + 1, y + 1);
                //yield return wait;
                uv[i] = new Vector2(x/(float)xSize, y/(float) ySize);
                tangents[i] = tangent;
            }
        }

        mesh.vertices = vertices;
        mesh.uv = uv;
        mesh.tangents = tangents;

        ////设置三角形定点信息
        //int[] triangles = new int[6];
        //triangles[0] = 0;
        //triangles[1] = xSize + 1;
        //triangles[2] = 1;

        ////绘制第二个三角形
        //triangles[3] = xSize +1;
        //triangles[4] = xSize + 2;
        //triangles[5] = 1;

        //mesh.triangles = triangles;
        int[] triangles = new int[xSize * ySize * 6];// 一个方形两个三角形  6个定点信息

        for (int ti = 0, vi = 0, y = 0; y < ySize; y++, vi++)
        {
            for (int x = 0; x < xSize; x++, ti += 6, vi++)
            {
                triangles[ti] = vi;
                triangles[ti + 3] = triangles[ti + 2] = vi + 1;
                triangles[ti + 4] = triangles[ti + 1] = vi + xSize + 1;
                triangles[ti + 5] = vi + xSize + 2;
            }
        }

        mesh.triangles = triangles;
        mesh.RecalculateNormals();
    }

你可能感兴趣的:(unity工作之余的总结)