【Unity x Mesh】网格生成笔记②-地形生成

参考Brackeys视频 https://www.youtube.com/watch?v=64NblGkAabk&t=1s

紧接上篇 【Unity x Mesh】网格生成笔记①-基础

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().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

你可能感兴趣的:(【Unity x Mesh】网格生成笔记②-地形生成)