Vector3 CubeToSphere(Vector3 cubePos)
{
float x2 = cubePos.x * cubePos.x;
float y2 = cubePos.y * cubePos.y;
float z2 = cubePos.z * cubePos.z;
float x = cubePos.x * Mathf.Sqrt(1.0f - (y2 + z2) / 2.0f + (y2 * z2) / 3.0f);
float y = cubePos.y * Mathf.Sqrt(1.0f - (z2 + x2) / 2.0f + (z2 * x2) / 3.0f);
float z = cubePos.z * Mathf.Sqrt(1.0f - (x2 + y2) / 2.0f + (x2 * y2) / 3.0f);
return new Vector3(x, y, z).normalized;
}
public void ConstructMesh()
{
Vector3[] vertices = new Vector3[resolution * resolution];
int[] triangles = new int[(resolution - 1) * (resolution - 1) * 6];
int triIndex = 0;
for (int y = 0; y < resolution; y++)
{
for (int x = 0; x < resolution; x++)
{
int i = x + y * resolution;
Vector2 percent = new Vector2(x, y) / (resolution - 1);
Vector3 pointOnUnitCube = localUp + (percent.x - .5f) * 2 * axisA + (percent.y - .5f) * 2 * axisB;
Vector3 pointOnUnitSphere = pointOnUnitCube.normalized;
vertices[i] = CubeToSphere(pointOnUnitCube); // pointOnUnitSphere;
if (x != resolution - 1 && y != resolution - 1)
{
triangles[triIndex] = i;
triangles[triIndex + 1] = i + resolution + 1;
triangles[triIndex + 2] = i + resolution;
triangles[triIndex + 3] = i;
triangles[triIndex + 4] = i + 1;
triangles[triIndex + 5] = i + resolution + 1;
triIndex += 6;
}
}
}
mesh.Clear();
mesh.vertices = vertices;
mesh.triangles = triangles;
mesh.RecalculateNormals();
}