- Home /
What is wrong with this mesh editing code?
I'm building a procedurally generated mesh, and need to fix normals at the chunk edges. I wrote this method to solve this for me, however, even tho in my Debugger screen the 2 vertex in world space are in the very same position, this code does not find them somehow. I mean the Vector3.Distance will be some random number, and sometimes I get crazy values which is not even the reality. For example when 2 vertices has the same position (-4, 0, 0) in world space, this code fids something (12, 0, 0) and I have no idea how.
void MixNormals(VoxelChunk chunk1, VoxelChunk chunk2)
{
Mesh mesh1 = null;
Mesh mesh2 = null;
if (chunk1.chunkObject.GetComponent<MeshFilter>() != null) mesh1 = chunk1.chunkObject.GetComponent<MeshFilter>().mesh;
if (chunk2.chunkObject.GetComponent<MeshFilter>() != null) mesh2 = chunk2.chunkObject.GetComponent<MeshFilter>().mesh;
if (mesh1 != null && mesh2 != null)
{
Vector3[] vertices1 = mesh1.vertices;
Vector3[] vertices2 = mesh2.vertices;
List<Vector3> normals1 = new List<Vector3>(mesh1.normals);
List<Vector3> normals2 = new List<Vector3>(mesh2.normals);
for (int i = 0; i < mesh1.vertexCount; i++)
{
for (int j = 0; j < mesh2.vertexCount; j++)
{
float dist = Vector3.Distance(chunk1.chunkObject.transform.position + vertices1[i], chunk2.chunkObject.transform.position + vertices2[j]);
if (dist <= vertexMergeMaxDistance)
{
normals1[i] = normals2[j] = (normals1[i] + normals2[j]) / 2;
}
}
}
}
}
On line 19. If your chunkObject.transform has any rotation or scaling then adding the position is not enough to find the world space position of the vertex. Use chunkObject.transform.TransformPoint(vertex)
They don't have any rotation, only translation. Also the problem was that I used a copy of the vertices array, and I had to use SetNormals at the end...