Search Unity

transform.position is wrong when parent has scale different than Vector3.one

Discussion in 'Scripting' started by cdr9042, Jul 1, 2020.

  1. cdr9042

    cdr9042

    Joined:
    Apr 22, 2018
    Posts:
    173
    I'm trying to raycast from the children Block, using their transform.position as origin point. When the Block's parent's localScale is Vector3.one, the Block's transform.position is correct. But when I try any different value, 0.8, 3.2, the transform.position is way off.

    In the example:
    the debug text "1 (0.7, 2.0, 0.0)" show the logged transform.position of Block (1). On the scene view, the red line simulate the raycast, the origin of the line is wrong, it's not at the center of the Block how I want it.

    I dragged the Block out of the parent to see its world position in the inspector, the real value is different from the transform.position that the code is using

    This is the code I used:

    Code (CSharp):
    1.              Debug.DrawRay(draggingPiece.Blocks[i].transform.position, Vector3.back * 10f, Color.red, 1f);
    2.              Debug.Log($"{i} {draggingPiece.Blocks[i].transform.position}");
    3.              RaycastHit2D raycast = Physics2D.Raycast(draggingPiece.Blocks[i].transform.position, Vector3.back, 10f, boardLayer);

    What's going on here?
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,911
    The transform position you see in the inspector is actually
    transform.localPosition
    in code. And yes, the parent's position, rotation, and scale will all affect the position of the child. This is expected and intended behavior. For this reason it's somewhat unusual to have a parent with a non-uniform scale as it can make working with its children complicated as you are seeing.

    The typical solution is to move the bits that need to be scaled to a leaf node in your hierarchy:

    • Parent with mesh filter/renderer (non-uniform scale)
    • Child

    To this:

    • Empty Parent (uniform scale)
    • Parent's old mesh filter/renderer (non-uniform scale)
    • Child
     
  3. cdr9042

    cdr9042

    Joined:
    Apr 22, 2018
    Posts:
    173
    thanks for the reply. I have figured it out. I have another script that changed the parent's localScale to 1,1,1 so my raycast script used that value. I removed that code and it works now