# How to Clamp Camera Rotation along y axis in a Fps Game?

Hello, I am making a fps game where camera is child of Player and here is the code -

So I am rotating player along his Y axis because he has to move forward,backward etc respective of his rotation, i am able to rotate camera along y axis as well but there is no limit, hence i tried clamping the rotY variable but it stops total rotation of Camera. Please help.

The problem with your current code is you are clamping the input values and not the angle of rotation. What you need to do is calculate a rotation and then clamp the angle on that before applying it to the camera.

Here’s a simply mouselook script to do that

``````using UnityEngine;

public class MouseLook : MonoBehaviour
{
public float Sensitivity = 2f;
public float YAxisAngleLock = 90f;

public Transform CameraTransform;

private Transform _playerTransform;

private Vector2 _rotation;
private Quaternion _playerTargetRot;
private Quaternion _cameraTargetRot;

private void Start()
{
_playerTransform = transform;
_playerTargetRot = _playerTransform.rotation;
_cameraTargetRot = CameraTransform.rotation;
}

private void Update()
{
_rotation.x = Input.GetAxis("Mouse X") * Sensitivity;
_rotation.y = Input.GetAxis("Mouse Y") * Sensitivity;

_playerTargetRot *= Quaternion.Euler(0f, _rotation.x, 0f);

_cameraTargetRot *= Quaternion.Euler(-_rotation.y, 0f, 0f);

_cameraTargetRot = LockCameraMovement(_cameraTargetRot);

_playerTransform.localRotation = _playerTargetRot;
CameraTransform.localRotation = _cameraTargetRot;
}

private Quaternion LockCameraMovement(Quaternion q)
{
q.x /= q.w;
q.y /= q.w;
q.z /= q.w;
q.w = 1.0f;

var angleX = 2.0f * Mathf.Rad2Deg * Mathf.Atan(q.x);

angleX = Mathf.Clamp(angleX, -YAxisAngleLock, YAxisAngleLock);

q.x = Mathf.Tan(0.5f * Mathf.Deg2Rad * angleX);

return q;
}
}
``````

Easy way of clamping camera rotation in unity