1
0

MeshGenerator.cs 1.8 KB

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