赞
踩
在项目中使用到了cube,但是unity自带的cube贴图的话,六个面方向,不是很理想,因此想到用代码生成一个mesh。mesh生成的时候需要设置三个数组 Vector3[] vertices,Vector2[] uv ,int[] triangles,其中 vertices和uv数组长度相同,triangles里的数值代表前面两个数组的下标,且必须是三的倍数。vertices里的是mesh的顶点位置是mesh的模型空间里的坐标,uv里是贴图坐标,xy取值范围都为[0,1],至于为什么,百度有很多,triangles里每三个成员代表的mesh顶点位置连接组成一个三角形,且必须是逆时针,否则渲出来的图片是反的。基于这些要求因此一个正方体的mesh这三个数组的定义最小形式应该是这样的Vector3[] vertices = new Vector3[24];Vector2[] uv = new Vector2[24];int[] triangles = new int[24];最后一个很重要的点,自己生成的mesh一定要调用一次那个mesh的RecalculateNormals()方法,否则渲染出来的mesh不能正确产生阴影!
每一个面的渲染顺序如图:
这里的顺序一定要在三个数组里一一对应!!
具体代码如下:
Vector3[] vertices = new Vector3[24]; vertices[0] = new Vector3(-0.5f, 0.5f, -0.5f); vertices[1] = new Vector3(0.5f, 0.5f, -0.5f); vertices[2] = new Vector3(0.5f, -0.5f, -0.5f); vertices[3] = new Vector3(-0.5f, -0.5f, -0.5f); vertices[4] = vertices[1]; vertices[5] = new Vector3(0.5f, 0.5f, 0.5f); vertices[6] = new Vector3(0.5f, -0.5f, 0.5f); ; vertices[7] = vertices[2]; vertices[8] = new Vector3(-0.5f, 0.5f, 0.5f); vertices[9] = vertices[5]; vertices[10] = vertices[1]; vertices[11] = vertices[0]; vertices[12] = vertices[8]; vertices[13] = vertices[0]; vertices[14] = vertices[3]; vertices[15] = new Vector3(-0.5f, -0.5f, 0.5f); vertices[16] = vertices[3]; vertices[17] = vertices[2]; vertices[18] = vertices[6]; vertices[19] = vertices[15]; vertices[20] = vertices[5]; vertices[21] = vertices[8]; vertices[22] = vertices[15]; vertices[23] = vertices[6]; // vertices[3] = new Vector3(0.5f, -0.5f, -0.5f); Vector2[] uv = new Vector2[24]; uv[0] = new Vector2(0, 1); uv[1] = new Vector2(1, 1f); uv[2] = new Vector2(1f, 0f); uv[3] = new Vector2(0, 0f); uv[4] = uv[0]; uv[5] = uv[1]; uv[6] = uv[2]; uv[7] = uv[3]; uv[8] = uv[0]; uv[9] = uv[1]; uv[10] = uv[2]; uv[11] = uv[3]; uv[12] = uv[0]; uv[13] = uv[1]; uv[14] = uv[2]; uv[15] = uv[3]; uv[16] = uv[0]; uv[17] = uv[1]; uv[18] = uv[2]; uv[19] = uv[3]; uv[20] = uv[0]; uv[21] = uv[1]; uv[22] = uv[2]; uv[23] = uv[3]; int[] triangles = { 0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7 ,8,9,10,8,10,11 ,12,13,14,12,14,15 ,16,17,18,16,18,19 ,20,21,22,20,22,23}; Mesh Cube = new Mesh { vertices = vertices, uv = uv, triangles = triangles }; //重新计算法线,代码生成的mesh必须有这一步否则,阴影效果不正常 Cube.RecalculateNormals();
以上代码生成的cube效果就自己运行贴图查看了,最后提一点,一定要自己用代码去测试一下单个三角形,正方形面片等。掌握以后,可以让cube的每一个面的方向,都由你的代码控制。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。