MeshGenerator.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using UnityEngine;
  2. using System.Collections;
  3. public static class MeshGenerator {
  4. public static MeshData GenerateTerrainMesh(float[,] heightMap, float heightMultiplier, AnimationCurve heightCurve, int levelOfDetail) {
  5. int width = heightMap.GetLength (0);
  6. int height = heightMap.GetLength (1);
  7. float topLeftX = (width - 1) / -2f;
  8. float topLeftZ = (height - 1) / 2f;
  9. int meshSimplificationIncrement = (levelOfDetail == 0)?1:levelOfDetail * 2;
  10. int verticesPerLine = (width - 1) / meshSimplificationIncrement + 1;
  11. MeshData meshData = new MeshData (verticesPerLine, verticesPerLine);
  12. int vertexIndex = 0;
  13. for (int y = 0; y < height; y += meshSimplificationIncrement) {
  14. for (int x = 0; x < width; x += meshSimplificationIncrement) {
  15. meshData.vertices [vertexIndex] = new Vector3 (topLeftX + x, heightCurve.Evaluate(heightMap [x, y]) * heightMultiplier, topLeftZ - y);
  16. meshData.uvs [vertexIndex] = new Vector2 (x / (float)width, y / (float)height);
  17. if (x < width - 1 && y < height - 1) {
  18. meshData.AddTriangle (vertexIndex, vertexIndex + verticesPerLine + 1, vertexIndex + verticesPerLine);
  19. meshData.AddTriangle (vertexIndex + verticesPerLine + 1, vertexIndex, vertexIndex + 1);
  20. }
  21. vertexIndex++;
  22. }
  23. }
  24. return meshData;
  25. }
  26. }
  27. public class MeshData {
  28. public Vector3[] vertices;
  29. public int[] triangles;
  30. public Vector2[] uvs;
  31. int triangleIndex;
  32. public MeshData(int meshWidth, int meshHeight) {
  33. vertices = new Vector3[meshWidth * meshHeight];
  34. uvs = new Vector2[meshWidth * meshHeight];
  35. triangles = new int[(meshWidth-1)*(meshHeight-1)*6];
  36. }
  37. public void AddTriangle(int a, int b, int c) {
  38. triangles [triangleIndex] = a;
  39. triangles [triangleIndex + 1] = b;
  40. triangles [triangleIndex + 2] = c;
  41. triangleIndex += 3;
  42. }
  43. public Mesh CreateMesh() {
  44. Mesh mesh = new Mesh ();
  45. mesh.vertices = vertices;
  46. mesh.triangles = triangles;
  47. mesh.uv = uvs;
  48. mesh.RecalculateNormals ();
  49. return mesh;
  50. }
  51. }