PlaneGenerator.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. using UnityEngine;
  2. public class PlaneGenerator : MonoBehaviour
  3. {
  4. private const int pqsResolution = 16;
  5. // Start is called once before the first execution of Update after the MonoBehaviour is created
  6. void Start()
  7. {
  8. var vertices = new Vector3[(pqsResolution + 1) * (pqsResolution + 1)];
  9. Vector2[] uv = new Vector2[(pqsResolution + 1) * (pqsResolution + 1)];
  10. var triangles = new int[(pqsResolution) * (pqsResolution) * 6];
  11. for (int x = 0, vertex = 0; x < pqsResolution + 1; x++)
  12. {
  13. for (int z = 0; z < pqsResolution + 1; z++, vertex++)
  14. {
  15. vertices[vertex] = new Vector3(x, 0, z);
  16. uv[vertex] = new Vector2((float)x / pqsResolution, (float)z / pqsResolution);
  17. }
  18. }
  19. int triangle = 0;
  20. for (int x = 1, vertex = 0; x < pqsResolution + 1; x++, vertex++)
  21. {
  22. for (int z = 1; z < pqsResolution + 1; z++, vertex++)
  23. {
  24. triangles[triangle] = vertex;
  25. triangles[triangle + 1] = vertex + pqsResolution + 2;
  26. triangles[triangle + 2] = vertex + pqsResolution + 1;
  27. triangles[triangle + 3] = vertex;
  28. triangles[triangle + 4] = vertex + 1;
  29. triangles[triangle + 5] = vertex + pqsResolution + 2;
  30. triangle += 6;
  31. }
  32. }
  33. var mesh = GetComponent<MeshFilter>();
  34. mesh.mesh.vertices = vertices;
  35. mesh.mesh.triangles = triangles;
  36. mesh.mesh.uv = uv;
  37. GetComponent<MeshCollider>().sharedMesh = mesh.mesh;
  38. mesh.mesh.RecalculateBounds();
  39. mesh.mesh.RecalculateNormals();
  40. }
  41. // Update is called once per frame
  42. void Update()
  43. {
  44. }
  45. }