How to restrict rotation

Hello, I’m trying to set limits to my rotation script, for instant, when I press “a” to rotate left and it reaches -90 it stops, and when I press “d” to rotate right and it reaches 90 it stops there, I know it is simple, but I can’t seem to make it work, even tho I tried all day with no success… I’d appreciate some help! :slight_smile:

Here is my script:

#pragma strict

public var speed : float = 1f;

function FixedUpdate ()


     if (Input.GetKey("d")) 
        transform.Rotate(-Vector3.up, speed * Time.fixedDeltaTime);
     if (Input.GetKey("a")) 
        transform.Rotate(Vector3.up, speed * Time.fixedDeltaTime);


Try this:

private var rotation = 0f;

function FixedUpdate()
    rotation += speed * Time.deltaTime;

    rotation -= speed * Time.deltaTime;

  rotation = Mathf.Clamp(rotation, -90, 90);

  var rot = transform.localEulerAngles;
  rot.y = rotation;
  transform.localEulerAngles = rot;

If you need a simple Y rotation limit this kind of works for me, example for camera rotation limited on Y axis. Attach component to camera, replace the “InputY” float with your input value from -1 to 1 and make a float for speed and rotationLimit variables and you should be good to go…

public void RotateCamera()
        Vector3 cameraEuler = transform.rotation.eulerAngles;
        if (cameraEuler.y > 180)
            cameraEuler.y -= 360;
        float desiredRot = cameraEuler.y + (inputY * speed);
        if (desiredRot > -rotationLimit && desiredRot < rotationLimit)
            transform.Rotate(Vector3.up, inputY * speed);