unity模型制作(一):绘制一个三角面

(不重要的前言:该博文为系列博文,每一篇有前后文关系,例如基类、组件的集成,如果发现有陌生组件和基类,请查看前面文章,本系列文章单纯应用unity的mesh来绘制模型,并未使用任何三方插件,文章内容、代码都是纯手打,望支持)

        前一篇简单说了unity模型制作原理,作为实践的第一步,做一个简单的demo,就绘制一个最简单的三角面。

        第一步:创建绘制脚本TriangleMesh

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TriangleMesh : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        //添加脚本
        MeshFilter  meshFilter = gameObject.AddComponent<MeshFilter>();

        //创建三个顶点
        Vector3[] vertices = new Vector3[] { Vector3.zero, Vector3.right, Vector3.forward };
        //创建一个三角面
        int[] triangles = new int[] { 0,2,1};
        
        //创建一组UV
        Vector2[] uvs = new Vector2[] { new Vector2(0, 0), new Vector2(1, 0), new Vector2(0, 1) };

        //添加数据
        meshFilter.mesh.vertices = vertices;
        meshFilter.mesh.triangles = triangles;
        meshFilter.mesh.uv = uvs;

        meshFilter.mesh.RecalculateBounds();
        meshFilter.mesh.RecalculateNormals();
        meshFilter.mesh.RecalculateTangents();

        //添加材质
        gameObject.AddComponent<MeshRenderer>().material = new Material(Shader.Find("Standard"));
    }
}

        第二步:创建一个空物体添加此脚本

         第三步:运行就可以看到一个三角面

简单回顾一下上一篇介绍,然后看这个三角形:

三个顶点vertices分别是P0,P1,P2, triangles只放了一组顶点顺序,所以就绘制出一个三角面,而很复杂的模型,其实最终也是由这样一个一个三角面拼起来的,比如unity自带的球体模型:

至于三角面012的顺序有什么影响,为什么不是021,还有uv有什么作用,后需文章再讲

猜你喜欢

转载自blog.csdn.net/u014261855/article/details/123509215