Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static function GenerateHeightmap (tex : Texture2D, size : Vector3, offset : Vector2, mat : Material)
- {
- GO = new GameObject ("terrain");
- GO.AddComponent("MeshFilter");
- GO.AddComponent("MeshRenderer");
- GO.renderer.material = mat;
- // Retrieve a mesh instance
- var mesh : Mesh = GO.GetComponent(MeshFilter).mesh;
- var width : int = 255;//Mathf.Min(tex.width, 255);
- var height : int = 255;//Mathf.Min(tex.height, 255);
- var y = 0;
- var x = 0;
- // Build vertices and UVs
- //This is kept as normal. 256^2 is more polygons than unity can handle.
- var vertices = new Vector3[height * width];
- var uv = new Vector2[height * width];
- var tangents = new Vector4[height * width];
- //scale of things..I hope!
- var uvScale = Vector2 (1.0 / (width - 1), 1.0 / (height - 1));
- var sizeScale = Vector3 (size.x / (width - 1), size.y, size.z / (height - 1));
- for (y=0; y<height ;y++)
- {
- for (x=0 ; x<width ;x++)
- {
- var pixelHeight = tex.GetPixel(x + offset.x, y + offset.y).a;
- var vertex = Vector3 (x + offset.x, pixelHeight, y + offset.y);
- vertices[y*width + x] = Vector3.Scale(sizeScale, vertex);
- uv[y*width + x] = Vector2.Scale(Vector2 (x + offset.x, y + offset.y), uvScale * 0.5); // *0.5 because max texture size is 512 (256 * 2)
- // Calculate tangent vector: a vector that goes from previous vertex
- // to next along X direction. We need tangents if we intend to
- // use bumpmap shaders on the mesh.
- var vertexL = Vector3( x-1, tex.GetPixel(x-1, y).a, y );
- var vertexR = Vector3( x+1, tex.GetPixel(x+1, y).a, y );
- var tan = Vector3.Scale( sizeScale, vertexR - vertexL ).normalized;
- tangents[y*width + x] = Vector4( tan.x, tan.y, tan.z, -1.0 );
- }
- }
- mesh.vertices = vertices;
- mesh.uv = uv;
- // Build triangle indices: 3 indices into vertex array for each triangle
- var triangles = new int[(height - 1) * (width - 1) * 6];
- var index = 0;
- for (y=0;y<height-1;y++) //-1
- {
- for (x=0;x<width-1;x++)
- {
- // For each grid cell output two triangles
- triangles[index++] = (y * width) + x;
- triangles[index++] = ((y+1) * width) + x;
- triangles[index++] = (y * width) + x + 1;
- triangles[index++] = ((y+1) * width) + x;
- triangles[index++] = ((y+1) * width) + x + 1;
- triangles[index++] = (y * width) + x + 1;
- }
- }
- // And assign them to the mesh
- mesh.triangles = triangles;
- // Auto-calculate vertex normals from the mesh
- mesh.RecalculateNormals();
- // Assign tangents after recalculating normals
- mesh.tangents = tangents;
- //THESE LINES ADD 5 SECONDS ROUGH TO LOAD
- //GO.AddComponent("MeshCollider");
- //GO.collider.sharedMesh = mesh;
- }
Advertisement
Add Comment
Please, Sign In to add comment