Rotate around vertically

Hello everyone,

I’m sure this is a simple fix that I’m too blind to see, but, I have a camera than I want to be able to pitch up and down, whilst looking at an object.

So, here is the code right now for the pitching.

Vector3 axis = new Vector3(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"), 0);

if (axis.y != 0)
{
	transform.RotateAround(new Vector3(0, 1, 0), Vector3.right, axis.y * camSpeed);
}

only issue is that it “sways” side to side and not up and down, no matter what I set. So, perhaps I’m just making a rookie mistake?

Cheers.

If I understood correctly you want to look at an object and be able to rotate around it on the camera Local X axis. If so then this works for me.

public class Look : MonoBehaviour {
	
	public GameObject targetObject;
	public float camSpeed = 1;
	
	// Use this for initialization
	void Start () {
		transform.LookAt(targetObject.transform.position);
	}
	
	// Update is called once per frame
	void Update () {

		float mouseY = camSpeed * Input.GetAxis("Mouse Y");
		
		if (targetObject != null)
		{				
			Vector3 localX = transform.TransformDirection(Vector3.right);
			
			transform.RotateAround(targetObject.transform.position, localX, mouseY);
		}
		
	}
}
1 Like

This code gave back the exact same result, I wish for it to rotate vertically, and yet this code causes it to orbit elliptically up and down. Any idea why that is?

I’m a bit unclear on what you want. Because what I gave you will allow you to rotate the camera around a given object whilst looking at it. You said you want an camera that can “pitch up and down, whilst looking at an object”. Do you mean you want a camera that elevates up in a straight line looking at the target but does not rotate about it?

Like this?

public class Look : MonoBehaviour {
	
	public GameObject targetObject;
	public float camSpeed = 15;
	
	// Use this for initialization
	void Start () {
		transform.LookAt(targetObject.transform.position);
	}
	
	// Update is called once per frame
	void Update () {

		float mouseY = camSpeed * Input.GetAxis("Mouse Y");
		
		if (targetObject != null)
		{				
			transform.Translate(new Vector3(0, mouseY, 0), Space.World);
			transform.LookAt(targetObject.transform.position);                  
		}
		
	}
}

Thanks! Works great.

Please use the like button instead of necroing a 12 year old thread :smile:

4 Likes