Question by
G_Robaina · Oct 21, 2021 at 12:24 AM ·
c#rotationquaternion
Clamp a rotation in unity
I have this code but I have not been able to find a decent solution to clamp the X axis between 2 angle values. How would it be done in this case?
public class CameraController : MonoBehaviour {
public float cameraSmoothness = 5f;
private Quaternion targetGlobalRotation;
private Quaternion targetLocalRotation = Quaternion.Identity;
private void Start(){
targetGlobalRotation = transform.rotation;
}
private void Update(){
targetGlobalRotation *= Quaternion.Euler(
Vector3.up * Input.GetAxis("Mouse X"));
targetLocalRotation *= Quaternion.Euler(
Vector3.right * -Input.GetAxis("Mouse Y"));
transform.rotation = Quaternion.Lerp(
transform.rotation,
targetGlobalRotation * targetLocalRotation,
cameraSmoothness * Time.deltaTime);
}
}
Comment
You're working with angles, not quaternions here. Since that is the case, you can just map mouse input to specific angles
public class CameraController : MonoBehaviour
{
[SerializeField] float _cameraSmoothness = 5f;
[SerializeField] Vector2 _horizontalRange = new Vector2( -60 , 60 );
[SerializeField] Vector2 _verticalRange = new Vector2( -30 , 30 );
float _horizontal, _vertical;
void Update ()
{
_horizontal = Mathf.Clamp( _horizontal + Input.GetAxis("Mouse X")*0.05f , -1f , 1f );
_vertical = Mathf.Clamp( _vertical - Input.GetAxis("Mouse Y")*0.05f , -1f , 1f );
var h = Quaternion.Euler( 0 , Mathf.Lerp( _horizontalRange.x , _horizontalRange.y , (1f+_horizontal)*0.5f ) , 0 );
var v = Quaternion.Euler( Mathf.Lerp( _verticalRange.x , _verticalRange.y , (1f+_vertical)*0.5f ) , 0 , 0 );
transform.localRotation = Quaternion.Slerp( transform.localRotation , h * v , _cameraSmoothness * Time.deltaTime );
}
}
Thank you very much for answering, I will try it!