Search Unity

Constraining Rotation

Discussion in 'Editor & General Support' started by yangmeng, Dec 11, 2006.

  1. yangmeng

    yangmeng

    Joined:
    Dec 5, 2006
    Posts:
    573
    Is there a way to constrain the rotation of one or more axis so that it can only rotate up to a certain amount? For example, allowing the Y axis to only rotate to 30 or -30 degrees?
    I wasn't able to find anything that looked like this in the scripting reference. Any ideas?
     
  2. scinortcele

    scinortcele

    Joined:
    Nov 30, 2006
    Posts:
    18
    I don't think that there's anything super-elegant [edit: I was wrong.], but you can always just write

    Code (csharp):
    1.  
    2. if (transform.rotation.y > 30)
    3. {
    4. transform.rotation.y = 30;
    5. }
    6. if (transform.rotation.y < -30)
    7. {
    8. transform.rotation.y = -30;
    9. }
    10.  
    It isn't beautiful, but it'll do the job.
     
  3. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    transform.rotation.y = Mathf.Clamp(transform.rotation.y, -30.0, 30.0);
     
  4. Aras

    Aras

    Unity Technologies

    Joined:
    Nov 7, 2005
    Posts:
    4,770
    This is almost true: you should use transform.eulerAngles though.

    transform.rotation.y would modify the 2nd component in the rotation quaternion, which does not have any intuitive effect.
     
  5. yangmeng

    yangmeng

    Joined:
    Dec 5, 2006
    Posts:
    573
    Thanks for your responses. The script with eulerAngles works but I am getting some choppy motion. I have other things affecting the physics of the objects though, so I will keep playing with it and see if I can smooth things out.
    Thanks again for your help.
     
  6. forestjohnson

    forestjohnson

    Joined:
    Oct 1, 2005
    Posts:
    1,370
    If the object has a rigidbody you are going to have to use rigidbody.AddForce(). For doing stuff like this ForceMode.VelocityChange is your freind. This constrains a rigidbody on it's y axis:

    Code (csharp):
    1. relativeAngularVelocity = transform.InverseTransformPoint(rigidbody.angularVelocity);
    2. relativeAngularVelocity.y = 0;
    3. newAngularVelocity = transform.TransformPoint(relativeAngularVelocity);
    4. difference = newAngularVelocity - rigidbody.angularVelocity;
    5. rigidbody.AddTorque(difference, ForceMode.VelocityChange);
     
    chaitanya007garg likes this.