First, recalculate normals give me inaccurate results. Try the below code, you can see the normals drawn perfectly when you look from the top of the cube.
And then change the normal calculation part with the unity recalculatenormals command and look from the top again where you will see the normals are not alligned.
using UnityEngine;
using System.Collections;
public class Cube : MonoBehaviour {
MeshFilter mF;
MeshRenderer mR;
Mesh mesh;
public Material mat;
const ushort CUBE_VERTICES = 8;
const ushort CUBE_TRIANGLES = 12;
Vector3[] vertices;
int[] indices;
Vector3[] normals;
Vector2[] uvs;
// Use this for initialization
void Start () {
gameObject.AddComponent(typeof(MeshFilter));
gameObject.AddComponent(typeof(MeshRenderer));
mesh = GetComponent<MeshFilter>().mesh;
//Vertices
vertices = new Vector3[CUBE_VERTICES]
{ new Vector3(-1, 1, -1), // 0
new Vector3(1, 1, -1), // 1
new Vector3(-1, -1, -1), // 2
new Vector3(1, -1, -1), // 3
new Vector3(-1, 1, 1), // 4
new Vector3(1, 1, 1), // 5
new Vector3(-1, -1, 1), // 6
new Vector3(1, -1, 1) // 7
};
mesh.vertices = vertices;
//Indices
indices = new int[CUBE_TRIANGLES*3]
{ 0, 1, 2, // side 1
2, 1, 3,
4, 0, 6, // side 2
6, 0, 2,
7, 5, 6, // side 3
6, 5, 4,
3, 1, 7, // side 4
7, 1, 5,
4, 5, 0, // side 5
0, 5, 1,
3, 7, 2, // side 6
2, 7, 6,
};
mesh.triangles = indices;
//Normals
normals = new Vector3[CUBE_VERTICES];
for(int i = 0; i < vertices.Length; i++) {
normals[i] = vertices[i].normalized;
}
mesh.normals = normals;
//UVs
uvs = new Vector2[CUBE_VERTICES];
for(int i = 0; i < uvs.Length; i++) {
uvs[i].x = Mathf.Asin(vertices[i].x) / Mathf.PI + 0.5f;
uvs[i].y = Mathf.Asin(vertices[i].y) / Mathf.PI + 0.5f;
}
mesh.uv = uvs;
//Materials
renderer.material = mat;
}
void Update () {
for(int i = 0; i < vertices.Length; i++) {
Debug.DrawRay(vertices[i], normals[i] * 2, Color.green);
}
}
}
2nd question: using the same code above, my uv mapping just doesnt work. Does anyone know how i can use spherical uv mapping on this cube?