Limit camera rotation with RotateAround


I’m struggling to find the right way to go about this. I think I’m down the wrong alley.
What I want is for my camera to rotate left and right (while left and right arrow keys are down).

This works OK:

if (Input.GetKey(KeyCode.LeftArrow)) {

        transform.RotateAround(centerPoint.position,Vector3(0,-1,0),20 * Time.deltaTime);


I want to limit the max angles that can be reached though. 30 degrees either way. I’m not sure what the best way to go about that is. From what I’ve read I think RotateAround maybe isn’t the way to do it, I need the effect that function gives though - I.E translating the movement at the same time to keep the focus in the center.

So, what would be the best way of achieving this?


  1. Figure out the axis you’re restricting rotation on.
  2. Clamp the rotation on that (-30, 30).

An example:

// after rotation
Vector3 objRotation = transform.rotation.eulerAngles;
float clampedY = Mathf.Clamp(objRotation.y, -30f, 30f);
transform.rotation.eulerAngles = new Vector3(objRotation.x, clampedY, objRotation.z);

The following would limit your orbit angle around a target relative to whatever your initial position with respect to that target is - not necessarily the target’s forward or other direction.

using UnityEngine;
using System.Collections;

public class OrbitCamera : MonoBehaviour {
	public float rotateSpeed = 20.0f;
	public float angleMax = 30.0f;
	public Transform target;
	private Vector3 initialVector = Vector3.forward;
	// Use this for initialization
	void Start () {
		if(target != null)
			initialVector = transform.position - target.position;
			initialVector.y = 0;
	// Update is called once per frame
	void Update () {
		if(target != null)
			float rotateDegrees = 0f;
			if (Input.GetKey(KeyCode.LeftArrow)) 
				rotateDegrees += rotateSpeed * Time.deltaTime;
			if (Input.GetKey(KeyCode.RightArrow)) 
				rotateDegrees -= rotateSpeed * Time.deltaTime;
			Vector3 currentVector = transform.position - target.position;
			currentVector.y = 0;
			float angleBetween = Vector3.Angle(initialVector, currentVector) * (Vector3.Cross(initialVector, currentVector).y > 0 ? 1 : -1);			
			float newAngle = Mathf.Clamp(angleBetween + rotateDegrees, -angleMax, angleMax);
			rotateDegrees = newAngle - angleBetween;
			transform.RotateAround(target.position, Vector3.up, rotateDegrees);

Hey guys!

I did the rotateAround method like you showed above, but can’t fix this shaking when near the angle limits.

alt text