- Home /
 
              This question was 
             closed Jan 23 at 02:49 AM by 
             Redsam121 for the following reason: 
             
 
            Too subjective and argumentative
 
               Question by 
               Redsam121 · Jan 22 at 01:17 PM · 
                camerarotationquaternionoffsetmathf.clamp  
              
 
              Limit Rotation of Camera around a player using keyboard
I'm trying to configure the camera to follow my player, but I'm having trouble limiting the rotation of the x angle as I don't want the camera above the head or under the feet.
This is the code so far:
 using System;
 using Unity.Mathematics;
 using UnityEngine;
 
 public class CameraFollow : MonoBehaviour
 {
     public Transform target;
     public Vector3 offset;
     [Range(0.01f, 1.0f)]
     public float smoothing = 0.125f;
     public bool Look = false;
     public float speed = 2.0f;
     private float rotY, rotX;
     void LateUpdate()
     {
         if (target)
         {
             Vector3 desiredPosition = target.position + offset;
             transform.position = Vector3.Slerp(transform.position, desiredPosition, smoothing);
 
             rotY = Input.GetAxis("Horizontal") * speed;
             rotX = Input.GetAxis("Vertical") * speed;
             //Limit the X rotation of the camera
             rotX = Mathf.Clamp(rotX, -10, 30);
             //Rotate camera
             offset = Quaternion.AngleAxis(rotY, Vector3.down) * offset;
             offset = Quaternion.AngleAxis(rotX, Vector3.right) * offset;
             if (Look)
             {
                 transform.LookAt(target);
             }
         }
     }
 }
 
 
              
               Comment
              
 
               
              Answer by Captain_Pineapple · Jan 22 at 01:25 PM
There are literally hunders of these questions on this forum. And they all boil down to the same 2 issues:
a unique rotation has multiple ways to be described by a set of euler angles.
When an axis rotation goes negative then unity will add 360 degrees. So
Mathf.Clampcan not be used here as the angle will always be between 0 and 360.