I want to add rotation limited in this script

I want to add rotation limited in this script, for example be able to change the rotation limited for example only rotates 25 degrees in local axis.

Any help please? :)

var gunSpeedNeg : int = 40;
var gunSpeedPos : int = 40;

function Update () 
{
    if(Input.GetKey("a"))
    {
        transform.Rotate(Vector3.right* gunSpeedNeg * Time.deltaTime);
    }

    if(Input.GetKey("d"))
    {
        transform.Rotate(Vector3.left* gunSpeedPos * Time.deltaTime);           
    }       
}

Thanks in advance for your help.

You can probably simplify this using Quaternion.RotateTowards, depending on your context.

var gunSpeed : float = 40;

private var rotation : Quaternion = Quaternion.identity;
private var left : Quaternion = Quaternion.AngleAxis(-25, Vector3.up);
private var right : Quaternion = Quaternion.AngleAxis(25, Vector3.up);

function Start ()
{
    // This piece of code will allow you to remember the origin.
    rotation = transform.rotation;
    left = rotation * left;
    right = rotation * right;
}

function Update () 
{
    var speed = gunSpeed * Time.deltaTime;

    if(Input.GetKey("a"))
    {
        rotation = Quaternion.RotateTowards(rotation, left, speed);
    }

    if(Input.GetKey("d"))
    {
        rotation = Quaternion.RotateTowards(rotation, right, speed);
    }

    transform.rotation = rotation;
}

Note that...

  • The script does turn 50 degrees (25 degrees positive and negative).
  • Other people might give better answers :)