Help limiting Camera rotation, spinning out of control.

Got camera code that kind of works but it rotates weird when i spin the courser. i think the main problem is lack of limits on the cameras vertical rotation. Help me put limits on it stopping it from moving more that 180 degrees vertically?

 void Update()
    {
        float horizontal = Input.GetAxis("Mouse X");
        transform.Rotate(new Vector3(0, horizontal * 10f, 0));

        float vertical = Input.GetAxis("Mouse Y");
        transform.Rotate(new Vector3(vertical * -5f, 0, 0));
}

81465-capture.png

In your case, where you have “transform.Rotate(new Vector3(vertical * -5f, 0, 0));” you would replace it with a different kind of statement, i.e.

private float rotX = 0;

...
void Update ()
{
    float horizontal = Input.GetAxis ("Mouse X");
    transform.Rotate (new Vector3 (0, horizontal * 10f, 0));

    float vertical = Input.GetAxis ("Mouse Y");
    rotX += vertical * -5;
    rotX = Mathf.Clamp (rotX, -90, 90);    //This clamps the vertical rotation in a 180 degree angle
    transform.localRotation = Quaternion.Euler (new Vector3 (rotX, transform.localRotation.eulerAngles.y, transform.localRotation.eulerAngles.z));
}

This does essentially the same thing, but actually sets the rotation directly rather than using transform functions.