- Home /
Not able to clamp camera rotation
I am working in unity 2018.2.0x Improved Prefabs and using a camera look script for my fps controller that is similar to one I used in unity 2017.4. Everything is working fine except for clamping the camera. It just refuses to work! after applying the clamp using Mathf.Clamp(), the camera's x rotation (I am clamping the up-down motion of camera) just resets to 0 even if the minimum and maximum values I put in the clamp method are -80 and 80 respetively. Here is my script. Thanks for the help
using UnityEngine;
public class PlayerLook : MonoBehaviour
{
public float mouseSensitivity;
private Rigidbody rb;
public float cameraRotationLimit; //Is set to 80.0f
private void Start()
{
rb = GetComponentInParent<Rigidbody>();
}
private void Update()
{
RotateCam();
}
private void RotateCam()
{
float xRot = Input.GetAxis("Mouse X") * mouseSensitivity;
float yRot = Input.GetAxis("Mouse Y") * mouseSensitivity;
Vector3 targetRotCam = Vector3.zero;
Vector3 targetRotBody = Vector3.zero;
// Set our rotation and clamp it
yRot = Mathf.Clamp(yRot, -cameraRotationLimit, cameraRotationLimit);
targetRotCam.x -= yRot;
targetRotBody.y += xRot;
rb.MoveRotation(rb.rotation * Quaternion.Euler(targetRotBody));//this is working just fine
//Apply our rotation to the transform of our camera
transform.localEulerAngles = targetRotCam;
}
}
Answer by Spacejet13 · Aug 07, 2018 at 06:33 PM
Found out what was not working.... I was clamping the variable yRot, when I had to clamp targetRotCam.x.....also, moving the Vector3 declaration for targetRotCam outside as a class variable solved the jitter problem. here is the new and working code.
using UnityEngine;
public class PlayerLook : MonoBehaviour
{
public float mouseSensitivity;
private Rigidbody rb;
public float cameraRotationLimit;
private Vector3 targetRotCam = Vector3.zero;
private void Start()
{
rb = GetComponentInParent<Rigidbody>();
}
private void Update()
{
RotateCam();
}
private void RotateCam()
{
float xRot = Input.GetAxis("Mouse X") * mouseSensitivity;
float yRot = Input.GetAxis("Mouse Y") * mouseSensitivity;
Vector3 targetRotBody = Vector3.zero;
targetRotCam.x -= yRot;
targetRotBody.y += xRot;
// Set our rotation and clamp it
targetRotCam.x = Mathf.Clamp(targetRotCam.x, -cameraRotationLimit, cameraRotationLimit);
rb.MoveRotation(rb.rotation * Quaternion.Euler(targetRotBody));
//Apply our rotation to the transform of our camera
transform.localEulerAngles = targetRotCam;
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612172319im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Another Mathf.Clamp Not Working on Rotate? 1 Answer