How to properly offset mesh vertices relative to the transform?

Hello,

Let’s say I have a rectangular box and what I want to do is shift the mesh and move the transform, so that the transform ends up at one side of the rectangular box.

Like so:

I have tried many things, people suggest you have to use Transform.InverseTransformPoint() or TransformPoint(), or using a 4x4 matrix, but I can’t figure it out, the box ends up offset to the wrong position.

Here the code:

        private Mesh RecenterMesh()
        {
            Vector3 offset = TargetTransform.transform.position - transform.position;

            transform.position = TargetTransform.transform.position;

            Mesh mesh = meshFilter.sharedMesh;

            Vector3[] vertsOffset = new Vector3[mesh.vertices.Length];

            for (int i = 0; i < mesh.vertices.Length; i++)
            {
                vertsOffset[i] = mesh.vertices[i] - offset;
            }

            mesh.vertices = vertsOffset;
            meshColl.sharedMesh = meshFilter.sharedMesh;
            mesh.RecalculateBounds();
            return mesh;
}

Any idea where to use InverseTransformPoint() or so?
Thanks for your help.

Shouldn’t you be adding the “offset” not subtracting it in the code above?

Unless im missing the context, the easiest way would probably be to have the mesh as a child to the actual object. You can then move its transform relative to the parent such that the origin of the parent is at the desired location on the childs mesh. Working with the parent transform should be identical to what you are attempting?

Agreed. I’d personally assumed this wasn’t an option because “reasons”. :slight_smile: