UnknownUser
UnknownUser

Reputation: 327

How to clamp rotation on a vertical axis?

I am working on the object viewer like sketchfab in Unity and currently doing camera rotation using mouse. So far everything seems to work, but I would like to clamp the rotation on the vertical axis, but have some trouble accomplishing this.

This is how I've done my camera rotation:

[SerializeField] Transform camPivot = null;
[SerializeField] float     speed    = 850.0F;

private Quaternion      _camRot         { get; set; } = Quaternion.identity;
private float           _polar          { get; set; } = 0;
private float           _elevation      { get; set; } = 0;

void DoRotation()
{
    this._polar     += Input.GetAxis("Mouse X") * this.speed * Mathf.Deg2Rad;
    this._elevation -= Input.GetAxis("Mouse Y") * this.speed * Mathf.Deg2Rad;

    this._camRot = Quaternion.AngleAxis(this._elevation, Vector3.right);
    this._camRot = Quaternion.AngleAxis(this._polar, Vector3.up) * this._camRot;
}
private void Update()
{
    this.DoRotation();

    this.camPivot.localRotation = Quaternion.Slerp(this.camPivot.localRotation, this._camRot, Time.unscaledDeltaTime * 5.0F);
}

Also I want to always make sure z rotation is zero as I only need to rotate the camera pivot horizontally and vertically, I tried setting camPivot euler z value to 0, but it gives me some really weird behavior.

var euler = this.viewCamera.Pivot.eulerAngles; euler.z = 0.0f;
    this.viewCamera.Pivot.eulerAngles = euler;

enter image description here

Upvotes: 0

Views: 1070

Answers (1)

Ruzihm
Ruzihm

Reputation: 20249

A very simple solution is to clamp _elevation to ±90 using Mathf.Clamp:

void DoRotation()
{
    this._polar     += Input.GetAxis("Mouse X") * this.speed * Mathf.Deg2Rad;
    this._elevation -= Input.GetAxis("Mouse Y") * this.speed * Mathf.Deg2Rad;
    this._elevation = Mathf.Clamp(this._elevation, -90f, 90f);

    this._camRot = Quaternion.AngleAxis(this._elevation, Vector3.right);
    this._camRot = Quaternion.AngleAxis(this._polar, Vector3.up) * this._camRot;
}

Upvotes: 1

Related Questions