Search Unity

Change rotation of a gameobject, so that its child has same global rotation as another gameobject.

Discussion in 'Scripting' started by Compressed, Aug 23, 2016.

  1. Compressed

    Compressed

    Joined:
    Sep 20, 2014
    Posts:
    59
    I have 3 game objects in a scene:

    --Scene
    ----GameObject1
    ----GameObject2
    -------GameObject3(child of GameObject2)

    Each of those game objects has some random rotation.

    I need to rotate the GameObject2 in such way where global (not local) rotation of the GameObject3 is identical to the rotation of the GameObject1. (As in achieve state where: if(GameObject1.transform.rotation == GameObject3.transform.rotation) is true)

    The local rotation of the GameObject3 cannot be changed in any way at all, all rotation changes are done to the GameObject2.

    Thank you.
     
  2. unitynoob24

    unitynoob24

    Joined:
    Dec 27, 2014
    Posts:
    333
    Have you tried checking the GameObject1.transform.localRotation?
     
  3. Compressed

    Compressed

    Joined:
    Sep 20, 2014
    Posts:
    59
    Nope, that value is of no use in this problem.
     
  4. unitynoob24

    unitynoob24

    Joined:
    Dec 27, 2014
    Posts:
    333
  5. Compressed

    Compressed

    Joined:
    Sep 20, 2014
    Posts:
    59
    That merely gives me an angle in degrees between two rotations, which is of no use for the thing i need.
     
  6. unitynoob24

    unitynoob24

    Joined:
    Dec 27, 2014
    Posts:
    333
  7. jmjd

    jmjd

    Joined:
    Nov 14, 2012
    Posts:
    45
    What you need to do is get the quaternion that represents the rotation from the child object (gameObject3) to your target object (gameObject1). Then you apply that rotation to gameObject2. That will look something like this:

    Edit: I realized that this doesn't account for gameObject2's rotation. The above would only work if gameObject2's rotation was zero (Quaternion.identity). But since we're changing it's rotation to whatever we need anyway, the simple fix is to just clear it before we do our calculations!

    Code (CSharp):
    1. gameObject2.transform.rotation = Quaternion.identity;
    2. Quaternion rot = gameObject1.transform.rotation * Quaternion.Inverse(gameObject3.transform.rotation);
    3. gameObject2.transform.rotation *= rot;
    4.  
     
    Last edited: Aug 24, 2016
unityunity