Search code examples
unity-game-enginerotationquaternions

Keeping Rotation of one Axis and aligning others to Parent


I have a problem keeping one axis locked. I have two tools I can use to grab this mock-up needle like object.

Tool grabbing "needle"

I just need to be able to keep its rotation around itself (local y) and align the rest with the tool's rotation. Currently, however, I can only figure out how to rotate all the axes like so:

Tool having grabbed "needle"

The code just looks like this:

 case 1:
 this.transform.rotation = leftParent.transform.rotation;
 this.transform.SetParent (leftParent);
 break;
 case 2:
 this.transform.rotation = rightParent.transform.rotation;
 this.transform.SetParent (rightParent);
 break;

What i have tried:

  • Using .Set on both local and global rotation, keeping the y and/or the w rotation
  • = new Quaternion as local and global rotation, keeping the y and/or the w
  • Rotating the needle after matching the parent rotation
  • Rotating the needle after parenting it

Please let me know if there's something obvious I have missed. Thanks!


Solution

  • I think what you're looking for is Transform.localRotation or Tranform.localEulerAngles : you can find more about those here.

    In your case I'll do something like this (considering your "hand" object geometry is as expected) :

    case1 :
    //Adjust the rotation you want to keep here (I assume on Y axis in your case)
    transform.SetParent(leftParent);
    transform.localEulerAngles = new Vector3(0.0f, transform.localEulerAngles.y, 0.0f);
    break;
    case2 :
    //Adjust the rotation you want to keep here (I assume on Y axis in your case)
    transform.SetParent(rightParent);
    transform.localEulerAngles = new Vector3(0.0f, transform.localEulerAngles.y, 0.0f);
    break;
    

    By the way, the this keyword is not needed in your situation since transform alone refers to the Transform at which the script is attached.