unity---Mesh网格编程

Posted 格拉格拉

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了unity---Mesh网格编程相关的知识,希望对你有一定的参考价值。

目录

1.绘制一个3X3的面

 2.代码


unity---Mesh网格编程(一)

1.绘制一个3X3的面

前面说了mesh的基础知识点,现在绘制一个3X3的面

 2.代码

 using System.Collections;
using UnityEngine;

//脚本挂载到物体时,自动添加MeshFilter与MeshRenderer组件
[RequireComponent(typeof(MeshFilter), typeof(MeshRenderer))]
public class Mesh2 : MonoBehaviour

    public int X = 3, Y = 2;
    private Vector3[] _vertices;
    private Vector2[] _uv;
    private Vector3[] _normals;

    void Start()
    
        //新建Mesh
        Mesh mesh = new Mesh();
        MeshFilter filter = GetComponent<MeshFilter>();
        filter.mesh = mesh;
        mesh.name = "Mesh2";
        //顶点数
        _vertices = new Vector3[(X + 1) * (Y + 1)];
        //纹理数
        _uv = new Vector2[_vertices.Length];
        //法向量
        _normals = new Vector3[_vertices.Length];

        StartCoroutine(GeneratePlane(mesh));
    

    private IEnumerator GeneratePlane(Mesh mesh)
    
        yield return GetVertices();
        mesh.vertices = _vertices;
        mesh.uv = _uv;
        mesh.normals = _normals;
        yield return GetTriangles(mesh);
    


    int i =0;
    private IEnumerator GetVertices()
    
        for (int y = 0; y < Y + 1; y++)
        
            for (int x = 0; x < X + 1; x++)
            
                _vertices[i] = new Vector3(x, y);
                _uv[i] = new Vector2((float)x / X, (float)y / Y);
                _normals[i] = GetNormal(y);
                yield return new WaitForSeconds(0.2f);
                i++;
            
        
    

    private Vector3 GetNormal(int y)
    
        if (y % 2 == 0)
        
            return Vector3.up;
        
        else
        
            return Vector3.down;
        
    

    private IEnumerator GetTriangles(Mesh mesh)
    
        int[] triangles = new int[X * Y * 6];

        for (int startIndex = 0, y = 0, triangleIndex = 0; startIndex < _vertices.Length && y < Y && triangleIndex < triangles.Length; startIndex++)
        
            for (int x = 0; x < X; x++, startIndex++, triangleIndex += 6)
            
                //当前四边形的第一个三角形
                triangles[triangleIndex] = startIndex;
                triangles[triangleIndex + 1] = startIndex + X + 1;
                triangles[triangleIndex + 2] = startIndex + 1;
                mesh.triangles = triangles;
                yield return new WaitForSeconds(0.2f);

                //当前四边形的第二个三角形
                triangles[triangleIndex + 3] = startIndex + X + 1;
                triangles[triangleIndex + 4] = startIndex + X + 2;
                triangles[triangleIndex + 5] = startIndex + 1;

                mesh.triangles = triangles;
                yield return new WaitForSeconds(0.2f);
            
        
    


以上是关于unity---Mesh网格编程的主要内容,如果未能解决你的问题,请参考以下文章

unity---Mesh网格编程

unity---Mesh网格编程

unity---Mesh网格编程

unity---Mesh网格编程

unity---Mesh网格编程

unity---Mesh网格编程