使用Unity3D生成网格并加贴图

        在使用Unity3D进行开发时,我们通常需要生成自己的网格来进行控制,比如进行图像变形等等。本文将介绍如何在Unity3D中生成一个网格。

        首先,需要在空间中生成顶点,然后在定义三角面片顶点序号。生成网格的代码如下:

using UnityEngine;
using System.Collections;


public class MeshGeneration : MonoBehaviour
{


    Mesh mesh;
    Vector3[] vertices;
    Vector2[] uv;
    int[] triangles;
    Vector3[] normals;
    void Start()
    {
        gameObject.AddComponent<MeshFilter>();
        gameObject.AddComponent<MeshRenderer>();
        Texture img = (Texture)Resources.Load("tu");
        gameObject.GetComponent<Renderer>().material.mainTexture = img;
        mesh = new Mesh();
        int m = 5; //row  
        int n = 10;  //col  
        float width = 8;
        float height = 6;
        vertices = new Vector3[(m + 1) * (n + 1)];//the positions of vertices 
        normals = new Vector3[(m + 1) * (n + 1)];


        uv = new Vector2[(m + 1) * (n + 1)];
        triangles = new int[6 * m * n];
        for (int i = 0; i < vertices.Length; i++)
        {
            float x = i % (n + 1);
            float y = i / (n + 1);
            float x_pos = x / n * width;
            float y_pos = y / m * height;
            vertices[i] = new Vector3(x_pos, y_pos, 0);
            normals[i] = new Vector3(0,0,-1);
            float u = x / n;
            float v = y / m;
            uv[i] = new Vector2(u, v);




        }
        for (int i = 0; i < 2 * m * n; i++)
        {
            int[] triIndex = new int[3];
            if (i % 2 == 0)
            {
                triIndex[0] = i / 2 + i / (2 * n);
                triIndex[1] = triIndex[0] + 1;
                triIndex[2] = triIndex[0] + (n + 1);
            }
            else
            {
                triIndex[0] = (i + 1) / 2 + i / (2 * n);
                triIndex[1] = triIndex[0] + (n + 1);
                triIndex[2] = triIndex[1] - 1;


            }
            //三角形顶点顺序会影响显示方向
            triangles[i * 3] = triIndex[0];
            triangles[i * 3 + 1] = triIndex[2];
            triangles[i * 3 + 2] = triIndex[1];


        }
        mesh.vertices = vertices;
        mesh.uv = uv;
        mesh.triangles = triangles;
        mesh.normals = normals;
        this.GetComponent<MeshFilter>().mesh = mesh;
    }
   
}

        下图中的风景图片就是将贴图直接贴在网格上的结果。看上去效果和直接将贴图扔到一个plane上是一样的。但是我们可以控制网格顶点的数量,自由度大大增加。




posted @ 2016-11-18 20:07  雁回晴空  阅读(2506)  评论(0编辑  收藏  举报