SphereMesh.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using UnityEngine;
  2. using System.Collections;
  3. public class SphereMesh : MonoBehaviour
  4. {
  5. MeshFilter myMeshFilter;
  6. public float radius = 1;
  7. void Start()
  8. {
  9. myMeshFilter = GetComponent<MeshFilter>();
  10. Mesh ball = new Mesh();
  11. //顶点数组
  12. Vector3[] ballVertices = new Vector3[182];
  13. //三角形数组
  14. int[] ballTriangles = new int[1080];
  15. /*水平每18度、垂直每18度确定一个顶点,
  16. 顶部和底部各一个顶点,一共是9x20+2=182个顶点。
  17. 每一环与相邻的下一环为一组,之间画出40个三角形,一共8组。
  18. 顶部和底部各与相邻环画20个三角形,总三角形数量40x8+20x2=360,
  19. 三角形索引数量360x3=1080*/
  20. int verticeCount = 0;
  21. for (int vD = 18; vD < 180; vD += 18)
  22. {
  23. float circleHeight =
  24. radius * Mathf.Cos(vD * Mathf.Deg2Rad);
  25. float circleRadius =
  26. radius * Mathf.Sin(vD * Mathf.Deg2Rad);
  27. for (int hD = 0; hD < 360; hD += 18)
  28. {
  29. ballVertices[verticeCount] =
  30. new Vector3(
  31. circleRadius * Mathf.Cos(hD * Mathf.Deg2Rad),
  32. circleHeight,
  33. circleRadius * Mathf.Sin(hD * Mathf.Deg2Rad));
  34. verticeCount++;
  35. }
  36. }
  37. ballVertices[180] = new Vector3(0, radius, 0);
  38. ballVertices[181] = new Vector3(0, -radius, 0);
  39. ball.vertices = ballVertices;
  40. int triangleCount = 0;
  41. for (int j = 0; j < 8; j++)
  42. {
  43. for (int i = 0; i < 20; i++)
  44. {
  45. ballTriangles[triangleCount++] =
  46. j * 20 + i;
  47. ballTriangles[triangleCount++] =
  48. (j + 1) * 20 + (i == 19 ? 0 : i + 1);
  49. ballTriangles[triangleCount++] =
  50. (j + 1) * 20 + i;
  51. ballTriangles[triangleCount++] =
  52. j * 20 + i;
  53. ballTriangles[triangleCount++] =
  54. j * 20 + (i == 19 ? 0 : i + 1);
  55. ballTriangles[triangleCount++] =
  56. (j + 1) * 20 + (i == 19 ? 0 : i + 1);
  57. }
  58. }
  59. for (int i = 0; i < 20; i++)
  60. {
  61. ballTriangles[triangleCount++] =
  62. 180;
  63. ballTriangles[triangleCount++] =
  64. (i == 19 ? 0 : i + 1);
  65. ballTriangles[triangleCount++] =
  66. i;
  67. ballTriangles[triangleCount++] =
  68. 181;
  69. ballTriangles[triangleCount++] =
  70. 160 + i;
  71. ballTriangles[triangleCount++] =
  72. 160 + (i == 19 ? 0 : i + 1);
  73. }
  74. ball.triangles = ballTriangles;
  75. ball.RecalculateNormals();
  76. myMeshFilter.mesh = ball;
  77. }
  78. }