MeshGenerator.cs 2.2 KB

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