Object Pivot After Mesh Merge is not centered.
Hi All,
Was wondering why is this happening, here is the case: i've a "mesh combiner" attached to an object, within there're 3 mesh creators (i set faces amount and a width to create different shapes ie: triangles with 3, cube 4, circle 50).
In this example i've 3 meshes with 4 faces forming 3 cubes, so i need to combine their meshes on a single one, to create a "L" shape, here is the code:
public void combineMeshes() {
//save old position
Vector3 transformPosition = gameObject.transform.localPosition;
//set it to 0, or transform will be a mess.
gameObject.transform.localPosition = Vector3.zero;
Mesh mesh = GetComponent<MeshFilter>().sharedMesh;
//clean the mesh.
if (mesh == null)
{
mesh = new Mesh();
}
else
{
mesh.Clear();
}
Mesh finalMesh = new Mesh();
MeshFilter[] filters = GetComponentsInChildren<MeshFilter>(true);
CombineInstance[] combInstance = new CombineInstance[filters.Length-1];
for (int i = 0; i < filters.Length; i++)
{
if (filters[i].sharedMesh != gameObject.GetComponent<MeshFilter>().sharedMesh)
{
combInstance[i-1].subMeshIndex = 0;
combInstance[i-1].mesh = filters[i].sharedMesh;
combInstance[i-1].transform = filters[i].transform.localToWorldMatrix * transform.worldToLocalMatrix;
}
}
finalMesh.CombineMeshes(combInstance);
finalMesh.name = "final mesh";
GetComponent<MeshFilter>().sharedMesh = finalMesh;
gameObject.transform.localPosition = transformPosition;
}
here is the thing. the merge is done correctly, also editor reference axis is setted coorectly, BUT when i move the object within the scene there's an offset in the "mesh" pivot that makes me place the object in the wrong position. anyone know what im doing wrong?. Thx!
somwhere i read to set the object within a new one and use that collider, but the offset is still there... and is a little tricky for future use on my game. Here you can see the collider "centered" and obiously all positions are setted to "0" (selected go, and child go, not shape ones, because they need to be at custom pos to merge them).
Answer by Facu4060 · Nov 29, 2016 at 04:16 AM
Just figured out my error, was setting position to 0,0,0 to not mess it with matrix conversion, but childs where not positioned with 0,0,0 parent. i was placing them with the "L " figure, somewhere in the worldspace, so when i merged the meshes that pivot was based on childs position, not parent position which make sense.
should place the parent at the center position before mergin.