Search Unity

Limiting Rotation

Discussion in 'Scripting' started by Myollinir, Mar 10, 2011.

  1. Myollinir

    Myollinir

    Joined:
    Mar 2, 2011
    Posts:
    17
    Hey all,

    Does anyone know about the ability to limit how far an object can rotate in free space if you have control over it?

    I don't have a character controller... I simply have applied a script to my object because I'm already using a rigidbody.

    It is flying in the air, as a glider, and I only want it to be able to tilt over so far. At the moment you can rotate it 360 degrees like a cartwheel, but I would like to lock it at a certain point.

    Any info / examples?

    Thanks
     
  2. DanielQuick

    DanielQuick

    Joined:
    Dec 31, 2010
    Posts:
    3,137
  3. PrimeDerektive

    PrimeDerektive

    Joined:
    Dec 13, 2009
    Posts:
    3,090
    If you're using euler angles, its common to use Mathf.Clamp().

    For instance, in the default mouse orbit script they use a function called ClampAngle to limit the rotation on the y axis so you can't spin around in circles. Here's a truncated version for illustrative purposes:

    Code (csharp):
    1.  
    2. public var rotSpeed : float = 120.0;
    3. public var yMinLimit : float = -20;
    4. public var yMaxLimit : float = 80;
    5.  
    6. private var yRot : float = 0.0;
    7.  
    8. function Start(){
    9.     var angles = transform.eulerAngles;
    10.     yRot = angles.y;
    11. }      
    12.  
    13. function Update(){
    14.  
    15.     yRot -= Input.GetAxis("Mouse Y") * rotSpeed * 0.02;
    16.     y = ClampAngle(y, yMinLimit, yMaxLimit);
    17.    
    18.     transform.rotation = Quaternion.Euler(y, 0, 0);
    19.        
    20. }
    21.  
    22. static function ClampAngle (angle : float, min : float, max : float) {
    23.     if (angle < -360)
    24.         angle += 360;
    25.     if (angle > 360)
    26.         angle -= 360;
    27.     return Mathf.Clamp (angle, min, max);
    28. }
    29.  
     
  4. dart

    dart

    Joined:
    Jan 9, 2010
    Posts:
    211
    EDIT: Deleted my post. Legend answered the same thing while I was posting mine
     
  5. Myollinir

    Myollinir

    Joined:
    Mar 2, 2011
    Posts:
    17
    thank you so much for the fast responses guys!