Cannot Figure Out What Is Wrong With My Use Of Mathf.clamp

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

Wild guess is that roty probably has a value like 320f instead of -40f, before being clamped that is. Could that be it?

Your code doesn’t clamp the camera’s rotation overall, it only clamps the amount that the camera can rotate in a single frame.

1 Like

I’m certain my camera starts at 0 degrees, I reset it before I started writing the code.

Ohhh, I see that now. That was a very silly mistake on my part. I’ve changed it to this:

float camx = cam.transform.rotation.x;
camx = Mathf.Clamp(camx, -90f, 90f);

But unfortunately it still doesn’t seem to work…

What do you assign the camera rotation to?

Mouse X and Y axis.

Edit: Actually just mouse Y axis

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?

I thought float camx = cam.transform.rotation.x; would do that.

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