I was writing some code to create a spherical mesh, however it has some odd defects such as:
- This spiral going from one pole to the other
- This odd zone across the equator:
I was wandering what is causing those issues.
This is the code used to generate the sphere:
using UnityEngine;
using System.Collections;
public class ProceduralSphere : MonoBehaviour {
MeshFilter meshFilter;
Mesh mesh;
Vector3[] vertices;
int[] triangles;
public int N;
public float radius;
// Use this for initialization
void Start () {
meshFilter = GetComponent<MeshFilter>();
mesh = new Mesh();
mesh.name = "ProceduralSphere v1";
vertices = new Vector3[(N + 1) * N];
triangles = new int[N * N * 6];
GenerateSphere(N);
}
// Update is called once per frame
void Update () {
}
void GenerateSphere(int N){
//Generate sphere vertices
int vertCount = 0;
for(int i=0;i<=N;i++){
for(int j=0;j<N;j++){
vertices[vertCount] = SpherePoint(i, j);
vertCount++;
}
}
//Generate triangles from vertices
int triCount = 0;
vertCount = 0;
for(int i=0;i<N-1;i++){
for(int j=0;j<N;j++){
triangles[triCount] = vertCount;
triangles[triCount + 1] = vertCount + N + 1;
triangles[triCount + 2] = vertCount + 1;
triangles[triCount + 3] = vertCount + 1;
triangles[triCount + 4] = vertCount + N + 1;
triangles[triCount + 5] = vertCount + N + 2;
triCount += 6;
vertCount++;
}
vertCount++;
}
mesh.vertices = vertices;
mesh.triangles = triangles;
mesh.Optimize();
mesh.RecalculateNormals();
meshFilter.mesh = mesh;
}
Vector3 SpherePoint(int m, int n){
//(x, y, z) = (sin(Pi * m/M) cos(2Pi * n/N), sin(Pi * m/M) sin(2Pi * n/N), cos(Pi * m/M))
return new Vector3(Mathf.Sin(Mathf.PI*m/N)*Mathf.Cos(2*Mathf.PI*n/N)*radius,
Mathf.Sin(Mathf.PI m/N)*Mathf.Sin(2*Mathf.PI*n/N)*radius,
Mathf.Cos(Mathf.PI*m/N)*radius);
}
}