FPS camera with y-axis limit to certain angle

Solution 1:

You have to use Mathf.Clamp to do this. Below is what I use to rotate the camera up/down and left/right. You can modify the yMaxLimit and yMinLimit variables to the angles you want to limit it to. There should be no limit while moving in the x direction.

public float xMoveThreshold = 1000.0f;
public float yMoveThreshold = 1000.0f;

public float yMaxLimit = 45.0f;
public float yMinLimit = -45.0f;


float yRotCounter = 0.0f;
float xRotCounter = 0.0f;

Transform player;

void Start()
{
    player = Camera.main.transform;
}

// Update is called once per frame
void Update()
{
    xRotCounter += Input.GetAxis("Mouse X") * xMoveThreshold * Time.deltaTime;
    yRotCounter += Input.GetAxis("Mouse Y") * yMoveThreshold * Time.deltaTime;
    yRotCounter = Mathf.Clamp(yRotCounter, yMinLimit, yMaxLimit);
    //xRotCounter = xRotCounter % 360;//Optional
    player.localEulerAngles = new Vector3(-yRotCounter, xRotCounter, 0);
}