# Mapping a cube to a sphere

Hello,

According to the formula in this site, the following code should work. But i get funny results as the result is not a sphere but more like an oval. Can anyone see what the problem is?

I am using an average box object with 10 subdivisions on every side exported from 3d max.

``````using UnityEngine;
using System.Collections;

public class PlanetLOD : MonoBehaviour {

Mesh m;

// Use this for initialization
void Start () {
m = GetComponent<MeshFilter>().mesh;

Vector3[] vertices = m.vertices;
Vector3[] verticesN = m.vertices;
Vector3[] normals = m.normals;

for (int i = 0; i < vertices.Length; i++) {
verticesN[i].x = SphericalX (vertices[i].x, vertices[i].y, vertices[i].z);
verticesN[i].y = SphericalY (vertices[i].x, vertices[i].y, vertices[i].z);
verticesN[i].z = SphericalZ (vertices[i].x, vertices[i].y, vertices[i].z);
}
m.vertices = verticesN;
m.RecalculateNormals();
}

float SphericalX (float x, float y, float z) {
return x * Mathf.Sqrt ( 1.0f - y * y * 0.5f - z * z * 0.5f + y * y * z * z / 3.0f);
}
float SphericalY (float x, float y, float z) {
return y * Mathf.Sqrt ( 1.0f - z * z - 0.5f - x * x * 0.5f + z * z * x * x / 3.0f);
}
float SphericalZ (float x, float y, float z) {
return z * Mathf.Sqrt ( 1.0f - x * x - 0.5f - y * y * 0.5f + x * x * y * y / 3.0f);
}
}
``````

EDIT: Attached is a photo of the problem.

I don’t know why it doesnt work but I think it is much easier to transform the position with this formula (assuming cube is centered in (0,0,0)):

float Spherical (Vector3 vertex)
{
}

Okay, this code works. But still not quite right like a total sphere. I think im missing some scale thing here.
Can anyone help?

``````using UnityEngine;
using System.Collections;

public class PlanetLOD : MonoBehaviour {

Mesh m;

// Use this for initialization
void Start () {
m = GetComponent<MeshFilter>().mesh;

Vector3[] vertices = m.vertices;
Vector3[] verticesN = m.vertices;
Vector3[] normals = m.normals;

for (int i = 0; i < vertices.Length; i++) {
verticesN[i].x = SphericalX (vertices[i].x, vertices[i].y, vertices[i].z) *1.3F;
verticesN[i].y = SphericalY (vertices[i].x, vertices[i].y, vertices[i].z) *1.3F;
verticesN[i].z = SphericalZ (vertices[i].x, vertices[i].y, vertices[i].z) *1.3F;
}
m.vertices = verticesN;
m.RecalculateNormals();

}

float SphericalX (float x, float y, float z) {
return x * Mathf.Sqrt (1.0F - y*y * 0.5F - z*z * 0.5F + y*y*z*z/3.0F);
}
float SphericalY (float x, float y, float z) {
return y * Mathf.Sqrt (1.0F - z*z * 0.5F - x*x * 0.5F + z*z*x*x/3.0F);
}
float SphericalZ (float x, float y, float z) {
return z * Mathf.Sqrt (1.0F - x*x * 0.5F - y*y * 0.5F + x*x*y*y/3.0F);
}
}
``````

Well, the formula itself is supposed to return a normalized * radius result. There is somethin else.

EDIT: Oh sorry, now i understand what you mean But i need to use this formula.