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

Child of parent position wrong

Discussion in 'Scripting' started by BusyRobot, Mar 8, 2015.

  1. BusyRobot

    BusyRobot

    Joined:
    Feb 22, 2013
    Posts:
    148
    I'm trying to create a small square frame to appear next to my main player sprite, and then when the player moves the square moves with it. So I'm attaching the square as a child like this

    Code (CSharp):
    1. actionFrame.transform.parent = mainPlayer.transform
    But it's not working. For some reason the position of the square is a negative version of the players current position, so if the player is at 500,500 then the square will be -500,-500

    How can I make the square be at 0,0 and move with the player?

    (I've tried setting the squares position after to 0,0 but it doesn't work).
     
  2. Suddoha

    Suddoha

    Joined:
    Nov 9, 2013
    Posts:
    2,824
    The new position values represent the localPosition of the gameObject relative to the parent object.

    If you're actionFrame is positioned at 0,0 and your parent at 500,500, the 'origin' of the object's local coordinates will no longer be the world coordinates 0,0 after parenting, but the parent's world coordinates.

    So the world position 0,0 would now be -500,-500 in the vector space relative to the parent.
    The local position 0,0 of your child transform will translate to 500,500 in world space
     
  3. BusyRobot

    BusyRobot

    Joined:
    Feb 22, 2013
    Posts:
    148
    So I have to make my squares position the same as the target parent before making it a child of that parent? and then it's a child it's local/relative pos will be 0,0?
     
  4. Suddoha

    Suddoha

    Joined:
    Nov 9, 2013
    Posts:
    2,824
    Or attach it and assign Vector2.zero (Vector3.zero respectively) to the childs transform.localPosition. That should work as well.