Guest User

Unity, Procedurally generated terrain

a guest
Aug 13th, 2015
465
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.19 KB | None | 0 0
  1. static int sideWidth = 30;
  2.  
  3. public static void CreateMesh(){
  4.                 Vector3[] vertices = new Vector3[sideWidth*sideWidth];
  5.                 System.Random r = new System.Random();
  6.                 int seed = r.Next(10000);
  7.                
  8.                 for(int x = 0; x < sideWidth; x++){
  9.                         for(int y = 0; y < sideWidth; y++){
  10.                                 float height;
  11.                                 height = Mathf.PerlinNoise(x * 0.1f + seed,y * 0.1f + seed);
  12.                                 vertices[y + x * sideWidth] = new Vector3(x, height, y);
  13.                         }
  14.                 }
  15.                
  16.                 int[] indices = new int[(sideWidth - 1) * (sideWidth - 1) * 6];
  17.                
  18.                 for(int x = 0; x < sideWidth - 1; x++){
  19.                         for(int y = 0; y < sideWidth - 1; y++){
  20.                                 int location = x * sideWidth + y;
  21.                                 int index = x * (sideWidth - 1) + y;
  22.                                 indices[index * 6] = location;
  23.                                 indices[index * 6 + 1] = location + 1;
  24.                                 indices[index * 6 + 2] = location + sideWidth + 1;
  25.                                
  26.                                 indices[index * 6 + 3] = location;
  27.                                 indices[index * 6 + 4] = location + sideWidth + 1;
  28.                                 indices[index * 6 + 5] = location + sideWidth;
  29.                         }
  30.                 }
  31.  
  32.                 Vector2[] uvs = new Vector2[sideWidth*sideWidth];
  33.  
  34.                 for(int x = 0; x < sideWidth; x++){
  35.                         for(int y = 0; y < sideWidth; y++){
  36.                                 uvs[y + x * sideWidth] = new Vector2(1 /(float)sideWidth * x, 1 / (float)sideWidth * y);
  37.                         }
  38.                 }
  39.                        
  40.                 Mesh mesh = new Mesh();
  41.                 mesh.vertices = vertices;
  42.                 mesh.triangles = indices;
  43.                 mesh.uv = uvs;
  44.                 mesh.RecalculateNormals();
  45.                 GameObject.Find ("TerraformController").GetComponent<MeshFilter>().mesh = mesh;
  46.         }
Advertisement
Add Comment
Please, Sign In to add comment