Hi there, I’m fairly new to unity and C# and I cannot figure out how to properly use the mathF.Clamp function. I have tried many times and looked at many posts on the forums but simply cannot figure out what I am doing wrong. I want to clamp my camera’s x rotation between 90 and -90 degrees to prevent my player from looking behind themselves and the camera going upside down.
private void FixedUpdate()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0, moveVertical);
this.transform.Translate(movement * Time.deltaTime * speed);
float rotx = Input.GetAxis("Mouse X");
float roty = Input.GetAxisRaw("Mouse Y");
Vector3 rot = transform.eulerAngles;
Camera cam = gameObject.GetComponentInChildren<Camera>();
roty = Mathf.Clamp(roty, -90f, 90f);
transform.Rotate(0, rotx * sensH, 0); //Rotates character in direction of mouse movement multiplied by sensitivity
cam.transform.Rotate(-roty * sensV, 0, 0); //Rotates camera up and down depending on mouse
What I mean is- you posted some code that clamps a variable called camx and said that it didn’t work. (i.e. your camera rotation is still not clamping like you want). But are you assigning your camera rotation.x to camx anywhere? Otherwise, how do you expect clamping camx will have any effect on the Camera rotation?
No. That will not change the value of
cam.transform.rotation.x in any way. It only copies the value of cam.transform.rotation.x to camx but these two variables are not connected in any way. Whatever change you make to camx does not effect cam.transform.rotation.x