what if you wanted to clamp a rotation to be between 90 and 270, so that you could look up and down, but it flips the other way! this would happen when the quaternion value “0” is between the min clamp and max clamp. in this case, what would you do?
This is a recurrent error: localPosition is a Quaternion, a weird creature, and not those nice angles we see in the Inspector’s Rotation field - they’re actually localEulerAngles.
The best way to limit rotation is to save the initial localEulerAngles in a Vector3 variable and “rotate” the desired angle mathematically:
using UnityEngine;
using System.Collections;
public class CameraController : MonoBehaviour {
public int Sensitivity;
private float MouseY;
private Vector3 CameraAngle;
public GameObject CameraTarget;
void Start () {
CameraAngle = transform.localEulerAngles;
}
void Update () {
// Rotation controls
CameraAngle.x += Input.GetAxis("Mouse Y") * Sensitivity * Time.deltaTime;
CameraAngle.x = Mathf.Clamp(CameraAngle.x, -90, 90);
transform.localEulerAngles = CameraAngle;
}
This code takes care of the rotation control, but doesn’t affect position.