Search code examples
c#unity-game-enginemathvectorposition

Unity3D: Move the parent gameobject relative to the child


enter image description here

So, I have X and Y game objects. I have a vector Z = X - Y which is indicated by the green line.

Also, I have a Parent game object and it has a Child game object. How do I move the parent such that the child game object is at the Point Y

I tried,

                  Z -= new Vector3(child.localPosition.x, 0, child.localPosition.z);
                  Parent.transform.position = Z

which is not working as expected. Thank you!


Solution

  • The absolute movement you would need to apply to your children object C to move to Y is the vector Y - C. If you apply this absolute movement to the parent, the children will be moved the same amount because children move along with their parents. So you need to apply this absolute movement Y - C to the parent and you will hace C in the y position.

    For the case of names of objects "y" and "Child", and "this" being the parent object, this would be the move:

    void moveToYGameObject()
    {
        //total absolute movement you want to move
        Vector3 AbsoluteMovement = GameObject.Find("y").transform.position - 
        GameObject.Find("Child").transform.position;
        //add this vector to current parent's (along with child) position
        this.transform.position += AbsoluteMovement;
    }
    

    Should work also on 3D, your objects dont need to be in the XZ plane. If the question is "How do I move the parent such that the child game object is at the Point Y" the x gameobject and the Z vector do not play any roll for the question itself, soy I might be missing something.

    Hope that helps!