0
\$\begingroup\$

I have a child where I want the rotation to work like (parentRot, parentRot, 0).

So first I set its localRotation to 0, meaning it will get the parents rotation: child.localRotation = Quaternion.identity;

But how can I make sure the world rotation (not local) value of the z axis stays at 0?

\$\endgroup\$
  • \$\begingroup\$ I've notice that you tagged this question both as C# and UnityScript. Are you sure you need an answer which explains how to do this in the old, deprecated UnityScript scripting language? If you only need a solution for writing Unity scripts in C#, please don't use that tag. \$\endgroup\$ – Philipp Sep 18 at 10:23
1
\$\begingroup\$

Here's another way to think of it:

First, we figure out which direction in the parent space points toward world "up":

Vector3 parentSpaceUp = transform.parent.InverseTransformDirection(Vector3.up);

Then we orient ourselves to point forward in the parent's local coordinate, while aligning our own up vector as close as possible to this vertical:

transform.localRotation = Quaternion.LookRotation(Vector3.forward, parentSpaceUp);

Wherever possible, I like to use direction vectors and quaternions over Euler angles, both to avoid unnecessary trig functions, and also to make sure the code doesn't exhibit bugs at edge cases where the Euler angles wrap around.

\$\endgroup\$
  • \$\begingroup\$ excellent point, a much more elegant answer, IMO. There certainly is a good amount of overhead in converting Euler angles to quaternions. My answer was an attempt to provide a solution to mirror the question as best as possible for someone who may not be entirely familiar with quaternion algebra. I vote for this though, for elgance reasons. - Oh, and for the record, the solution I provided would not experience gimbal-lock related issues, as a quaternion can be described using euler angles and vice-versa. The trouble would come when accumulating euler angles, instead of direct conversion. \$\endgroup\$ – Jon Koelzer Sep 11 at 3:18
0
\$\begingroup\$

I have no idea what you're trying to do, but this does precisely what you described.

public class AxisLock : MonoBehaviour
{
    void Update()
    {

        Vector3 target;
        target.x = transform.parent.eulerAngles.x;
        target.y = transform.parent.eulerAngles.y;
        target.z = 0;
        transform.rotation = Quaternion.Euler(target);
    }
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.