Search Unity

How to set a single-axis rotation and not change the others axes

Discussion in 'Physics' started by GeekOverdrive, Mar 5, 2019.

  1. GeekOverdrive

    GeekOverdrive

    Joined:
    Dec 31, 2018
    Posts:
    8
    First off, I've spent the last three days researching how to solve this issue. I've looked at this video on quaternions, dozens of posts on setting quaternions with Euler angles (and not), avoiding gimbal lock, and how they're problematic when used to alter one axis and maintain the same rotation on the other axes (or something like that).


    Here's what I'm trying to do:

    1) I need to get the z-axis angle of my object and do some calculations with it. It shouldn't change unless specified by the object's code or done so manually.
    2) With that calculation handy, I get (what should be) the new x-axis angle.
    3) I get the object's localRotation.eulerAngles, and place them in PrevYAngle and PrevZAngle.
    4) I set the rotation of my object via Quaternion.Euler(NewXAngle, PrevYAngle, PrevZAngle)

    The next time around, somehow the Y and Z axes have changed. This throws off the calculation. Needless to say, that's a problem. One thing I should point out: The Y and Z axes seem to be proportionate. When I change the values with the calculation (based on the position of another object, and a few other things), they stay the same value at the same position. I.e, if I move the object, the values change. But if I move it back, the values go back to how they were when the object was at that position.


    Here are the basics in code of what I'm trying to do:

        Vector3 oldAngles = child.localEulerAngles;
    float angle = child.eulerAngles.z;
    // in the case of my test, (child) is parented by an object who's Euler rotation is (0, 0, 20). The child isn't rotated separately atm, so it should be (20).

    // do the calculation. Use it, among some trigonometry and other things, to get a proportion of -1 to 1 and set to myProportion.
    float XAngleProp = Mathf.Abs(myProportion - 1);
    // absolute - 1 to get the value between 0 and 2.

    float rotationAngle = Mathf.floor(90 * XAngleProp);

    Quaternion rot = Quaternion.Euler(rotationAngle, oldAngles.y, oldAngles.z);

    child.localRotation = rot;


    The child rotates correctly (as in it doesn't spasm), but my calculation is thrown off by the changing z-axis value. I also don't quite understand quite how the z-axis value is changing, but the child does not appear to actually be rotating on the z-axis at all. I have an idea that it may be changing in relation to the other axes, but I feel like that wouldn't be intuitive.

    If someone can provide me a way to change the x-axis of my child object while maintaining the set value of its y and z axes (or explain to my why this is happening and how I can achieve my goal), I'd be very much appreciative.