参考Brackeys视频 https://www.youtube.com/watch?v=64NblGkAabk&t=1s
using UnityEnginel
[RequireComponent(typeof(MeshFilter))]
public class MeshGenerator: MonoBehaviour{
Mesh mesh;
Vector3[] vertices;
int[] triangles;
// vertix 的数量是size+1
public int xSize = 20;
public int zSize =20;
void Start(){
mesh = new Mesh();
GetComponent<MeshFilter>().mesh = mesh;
StartCoroutine(CreateShape());
}
void Update()
{
UpdateMesh();
}
IEnumerator CreateShape()
{
//有这么多的顶点
vertices = new Vector3[(xSize + 1 ) * (zSize +1)];
//可以把index放在for循环参数中
for( int i = 0,int z = 0; z<=zSize; z++)
{
for(int x = 0; x < xSize; x++)
{
//随机数,perlin noise
float y = Mathf.PerlinNoise(x*.3f,z)*2f;
vertices[i] = new Vector3 (x,y,z);
i++;
}
}
triangles = new int[xSize * zSize*6];
int vert = 0;
int tris = 0;
for (int z = 0; z< zSize;z++)
{
for(int x = 0; x<xSize; x++)
{
triangles[tris+0] = vert+ 0;
triangles[tris+1]= vert + xSize + 1;
triangles[tris+2]= vert + 1;
triangles[tris+3] =vert +1;
triangles[tris+4] =vert +xSize+1;
triangles[tris+5] =vert +xSize+2;
vert++;
tris+=6;
yield return new WaitForSecond(0.05f);
}
//不加的话会有重叠?
vert++;
}
}
void UpdateMesh()
{
mesh.Clear();
mesh.vertices = vertices;
mesh.triangles = triangles;
// 光线更新,法线的角度吸收
mesh.ReCalculateNormal();
}
//似乎会自动运行这个
void OnDrawGizmos(){
if(vertices == null)
return;
for (int i = 0; i < vertices.Length; i++)
{
Gizmos.DrawSphere(vertices[i], .1f)
}
}
}