七、Unity 生成几种常用模型mesh-----SphereShape(球)

1、获得顶点的数据集合

 protected override Vector3[] GetVertices()
        {
            var curIndex = 0;
            var arrayLen = (_latitude + 1) * (_longitude + 1);
            var vertices = new Vector3[arrayLen];
            for (var lat = 0; lat <= _latitude; lat++)
            {
                //经线角度的取值范围是0~180度
                var latRad = lat * 1.0f / _latitude * Mathf.PI;
                var latCos = Mathf.Cos(latRad);
                var latSin = Mathf.Sin(latRad);
                for (var lon = 0; lon <= _longitude; lon++)
                {
                    //纬线角度的取值范围是0~360度
                    var lonRad = lon * 1.0f / _longitude * Mathf.PI * 2;//每一圈的最后一个点和第一个点重合(设置UV的坐标)
                    var lonCos = Mathf.Cos(lonRad);
                    var lonSin = Mathf.Sin(lonRad);
                    vertices[curIndex++] = new Vector3(latSin * lonCos, latCos, latSin * lonSin) * _radius - _vertexOffset;
                }
            }
            return vertices;
        }

2、获得法线方向的数据集合

protected override Vector3[] GetNormals()
        {
            var curIndex = 0;
            var vertices = Vertices;//获得当前的顶点
            var normals = new Vector3[vertices.Length];
            foreach (var vertex in vertices)
            {
                normals[curIndex++] = (vertex + _vertexOffset).normalized;
            }
            return normals;
        }

3、获得三角面顶点的索引

 protected override int[] GetTriangles()
        {
            var curIndex = 0;
            var arrayLen = _latitude * _longitude * 3 * 2;
            var triangles = new int[arrayLen];
            //侧面
            for (var lat = 0; lat < _latitude; lat++)
            {
                for (var lon = 0; lon < _longitude; lon++)
                {
                    var current = lat * (_longitude + 1) + lon;
                    var next = current + _longitude + 1;

                    triangles[curIndex++] = current;
                    triangles[curIndex++] = current + 1;
                    triangles[curIndex++] = next;

                    triangles[curIndex++] = next;
                    triangles[curIndex++] = current + 1;
                    triangles[curIndex++] = next + 1;
                }
            }
            return triangles;
        }

4、获得UV坐标的数据集合

protected override Vector2[] GetUVs()
        {
            var curIndex = 0;
            var arrayLen = (_latitude + 1) * (_longitude + 1);
            var uvs = new Vector2[arrayLen];
            for (var lat = 0; lat <= _latitude; lat++)
                for (var lon = 0; lon <= _longitude; lon++)
                    uvs[curIndex++] = new Vector2((float)lon / _longitude, 1f - (float)lat / _latitude);
            return uvs;
        }

效果如下:七、Unity 生成几种常用模型mesh-----SphereShape(球)_第1张图片
gitee地址:https://gitee.com/pangdudu010...

你可能感兴趣的:(unity)