
上图是效果
一.关于mesh的意义
有了mesh网格,物体才能被渲染出来。
(1)mesh中包含顶点,
mesh.vertices
(2)顶点对应的uv(一张图的uv左下角00,右上角11)
mesh.uv
(3)指定每个三角面对应的顶点位置(顺时针方向culling back:默认不绘制背面)
mesh.triangles
(4)切线信息
mesh.tangents
(5)法线信息
mesh.normals
还有其它就不再说了,这里主要是 顶点“veticles”,“uv”, 三角面“triangles”!!!
二.一个物体的正常渲染流程:
顶点坐标 -》顶点对应的UV坐标-》三角面对应的顶点位置
三.设置顶点的坐标和顺序可以多种多样,但是条条大路通罗马
例如:一个长方体:
设置顶点坐标的方式:从上往下 从左往右 等
怎么从0到1绘制一个简单的长方形有很多教程,解释的很清楚mesh编程入门精讲
有两个函数注意一下:
(1)重置法线垂直于当前的三角面
mesh.RecaculateNormals()
(2)将当前mesh,拆分成3个submesh
mesh.submeshCount = 3
mesh.SetTriangles(trianglesX, 0);
mesh.SetTriangles(trianglesY, 1);
mesh.SetTriangles(trianglesZ, 2);
并且 MeshRender中的Materials中的 第一个material对应渲染第一个submesh;第二个material对应渲染第二个;。。。。
四介绍绘制一个立方体的思路:
(1)计算顶点的个数:
//三个面的交点
int conerVerticles = 8;
// 两个面的交点
int edgeVerticles = (xSize + ySize + zSize - 3) * 4;
// 上中下 三个面的点 (共6个面,所以要乘以2)
int faceVerticles = ((xSize - 1) * (ySize - 1) + (xSize - 1) * (zSize - 1) + (ySize - 1) * (zSize - 1)) * 2;
// 总顶点数量
int totalVerticles = conerVerticles + edgeVerticles + faceVerticles;
Vector3[] veticles = new Vector3[totalVerticles];
(2)在形成三角形的时需要用到三角形顶点的个数:
有n个四边形,那么总的三角形顶点数目: 4*n
//一共多少四边形
int quads = (xSize * zSize + xSize * ySize + zSize * ySize) * 2;
// 三角面的顶点数
int totalCount = quads * 6;
int[] triangles = new int[totalCount];
(3)计算下一个triangles的索引:
// 返回值是 :下一个triangles的索引
static int SetQuad(int[]triangles,int t,int v00,int v10,int v01,int v11)
{
triangles[t] = v00;
triangles[t + 1] = triangles[t+4] = v01;
triangles[t + 2] = triangles[t+3] = v10;
triangles[t + 5] = v11;
return t + 6;
}
(4)其它的就没有可讲的了,都是如何拼接三角形形成mesh。顺序和方法比较多。。思想都是一样的。
下面附详细代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(MeshFilter), typeof(MeshRenderer))]
public class SplittingMesh : MonoBehaviour
{
public int xSize, ySize, zSize;
public int Roundness;
private Mesh mesh;
private Vector3[] vertices;
private Vector3[] normals;
private Color32[] CubeUV;
void Start()
{
GenerateVertices();
StartCoroutine(GenerateTriangles());
}
/// <summary>
/// 生成顶点
/// </summary>
void GenerateVertices()
{
GetComponent<MeshFilter>().mesh = mesh = new Mesh();
mesh.name = "Procedural Cube ";
int cornerVertices = 8; //八个角 八个顶点
int edgeVertices = (xSize +ySize +zSize -3)*4; //不考虑顶点公用的话 应该是 (xSize+ySize+zSize +1)*4
int faceVertices = (
(xSize-1)*

本文围绕Unity中Mesh编程展开,介绍了Mesh的意义,包含顶点、uv、三角面等信息。阐述了物体正常渲染流程,提及设置顶点坐标的多种方式及相关函数。还介绍了绘制立方体的思路,如计算顶点和三角形顶点个数等,最后附上详细代码。
最低0.47元/天 解锁文章
5640

被折叠的 条评论
为什么被折叠?



