Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question How to properly offset mesh vertices relative to the transform?

Discussion in 'Scripting' started by Kiux01, Aug 19, 2023.

  1. Kiux01

    Kiux01

    Joined:
    Jan 21, 2013
    Posts:
    18
    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:
    unity_mesh_transform.png

    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:

    Code (CSharp):
    1.  
    2.         private Mesh RecenterMesh()
    3.         {
    4.             Vector3 offset = TargetTransform.transform.position - transform.position;
    5.  
    6.             transform.position = TargetTransform.transform.position;
    7.  
    8.             Mesh mesh = meshFilter.sharedMesh;
    9.  
    10.             Vector3[] vertsOffset = new Vector3[mesh.vertices.Length];
    11.  
    12.             for (int i = 0; i < mesh.vertices.Length; i++)
    13.             {
    14.                 vertsOffset[i] = mesh.vertices[i] - offset;
    15.             }
    16.  
    17.             mesh.vertices = vertsOffset;
    18.             meshColl.sharedMesh = meshFilter.sharedMesh;
    19.             mesh.RecalculateBounds();
    20.             return mesh;
    21. }
    Any idea where to use InverseTransformPoint() or so?
    Thanks for your help.
     
  2. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    10,468
    Shouldn't you be adding the "offset" not subtracting it in the code above?
     
    bugfinders likes this.
  3. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,588
    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?
     
    Bunny83, wideeyenow_unity and MelvMay like this.
  4. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    10,468
    Agreed. I'd personally assumed this wasn't an option because "reasons". :)